-
This is mostly an academic question as I know I can do this with ctypes pretty easily Certain WIn32 APIs require that you pass in a delegate/callback function as part of the API call. For example EnumWindows requires:
Where lpEnumFunc is a application defined callback. This is my understanding as to how IronPython would expect you to P/invoke th function and call it with a delegate: import clr
clr.AddReference("System")
clr.AddReference("System.Core") # Add this reference for LINQ support
import System
from System import IntPtr, Func, UInt64
from System.Runtime.InteropServices import DllImportAttribute, PreserveSigAttribute
import clrtype
from enum import Enum
EnumWindowsProc = Func[IntPtr, IntPtr, bool]
class NativeMethods(object, metaclass=clrtype.ClrClass):
__metaclass__ = clrtype.ClrClass # https://github.com/IronLanguages/ironpython3/issues/836
DllImport = clrtype.attribute(DllImportAttribute)
PreserveSig = clrtype.attribute(PreserveSigAttribute)
@staticmethod
@DllImport("user32.dll", SetLastError=True)
@PreserveSig()
@clrtype.accepts(EnumWindowsProc, IntPtr)
@clrtype.returns(UInt64)
def EnumWindows(lpEnumFunc, lParam: IntPtr):raise NotImplementedError("No EnumWindow")
def outputwindow(hwnd, lParam):
print("callback called", hwnd)
return True
# Create an instance of the delegate using the callback function
delegate_instance = EnumWindowsProc(outputwindow)
# Call the EnumWindows function with the delegate instance as the callback
NativeMethods.EnumWindows(delegate_instance, IntPtr.Zero)
print("testing complete") However, this throws an error because generic types cannot be marshalled and |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Digging through the codebase a bit it looks like you can create non-generic delegates in at least two ways: clr.AddReference("Microsoft.Dynamic")
from Microsoft.Scripting.Generation import Snippets
EnumWindowsProc = Snippets.Shared.DefineDelegate("MyDelegate", bool, IntPtr, IntPtr)
clr.AddReference("IronPython")
from IronPython.Runtime.Operations import PythonOps
EnumWindowsProc = PythonOps.MakeNewCustomDelegate(System.Array[System.Type]([IntPtr, IntPtr, bool])) I wonder if one of these would be a good fit for a helper in |
Beta Was this translation helpful? Give feedback.
Digging through the codebase a bit it looks like you can create non-generic delegates in at least two ways:
I wonder if one of these would be a good fit for a helper in
clrtype
(probably theSnippets
version)...