I am using some interesting code to perform dynamic unmanaged dll calling:
Imports System.Runtime.InteropServices
Module NativeMethods
Declare Function LoadLibrary Lib "kernel32" Alias "LoadLibraryA" (ByVal dllToLoad As String) As IntPtr
Declare Function GetProcAddress Lib "kernel32" (ByVal hModule As IntPtr, ByVal procedureName As String) As IntPtr
Declare Function FreeLibrary Lib "kernel32" (ByVal hModule As IntPtr) As Boolean
End Module
Module Program
<UnmanagedFunctionPointer(CallingConvention.Cdecl)> _
Delegate Function MultiplyByTen(ByVal numberToMultiply As Integer) As Integer
Sub Main()
Dim pDll As IntPtr = NativeMethods.LoadLibrary("MultiplyByTen.dll")
Dim pAddressOfFunctionToCall As IntPtr = NativeMethods.GetProcAddress(pDll, "MultiplyByTen")
Dim multiplyByTen As MultiplyByTen = DirectCast(Marshal.GetDelegateForFunctionPointer(pAddressOfFunctionToCall, GetType(MultiplyByTen)), MultiplyByTen)
Dim theResult As Integer = multiplyByTen(10)
Console.WriteLine(theResult)
NativeMethods.FreeLibrary(pAddressOfFunctionToCall)
End Sub
End Module
I want to be able to change the parameter signature and type of the delegate to void or to a function returning integer, string, or boolean.
Basically, I want my program (interpreter) to be able to call upon any method in any unmanaged dll that the programmer has access to... since I cannot predict what method the programmer will want to have access to - I'd like to enable them to have access to any useful method.
This seems like it's possible in vb.net - perhaps with reflection? - but I'm just not sure how to do it.
--- EDIT: Here's what I've come up with:
<UnmanagedFunctionPointer(CallingConvention.Cdecl)> _
Delegate Function DelegateInteger(<[ParamArray]()> ByVal args() As Object) As Integer
...
Dim GetStdHandle = NativeDllCallIntegerMethod("kernel32", "GetStdHandle", -11)
...
Function NativeDllCallIntegerMethod(ByVal DllPath As String, ByVal DllMethod As String, ByVal ParamArray Arguments() As Object) As Integer
Dim pDll As IntPtr = NativeMethods.LoadLibrary(DllPath)
Dim pAddressOfFunctionToCall As IntPtr = NativeMethods.GetProcAddress(pDll, DllMethod)
Dim IntegerFunction As DelegateInteger = DirectCast(Marshal.GetDelegateForFunctionPointer(pAddressOfFunctionToCall, GetType(DelegateInteger)), DelegateInteger)
Dim theResult As Object = IntegerFunction.DynamicInvoke(Arguments)
NativeDllCallIntegerMethod = theResult
NativeMethods.FreeLibrary(pAddressOfFunctionToCall)
End Function
This raises a complaint on the line with 'Dim theResult = ...' on it. The error is "Object of type 'System.Int32' cannot be converted to type 'System.Object[]'."
I seem to be getting somewhere but... where? I don't really know.
I've got it. I can now dynamically call methods: