Function delegate from a procedure address

Bucky

Well-known member
Joined
Dec 23, 2001
Messages
791
Location
East Coast
User Rank
*Expert*
Ive been trying to replicate some C++ code in VB.NET. The
C++ code gets a function address by using GetProcAddress, then
casts that into a delegate that then calls a callback function in
the code. So far I can correctly get the procedure address into
an IntPtr variable, but now Im trying to create an instance of a
function delegate based on this address. DirectCast wont take
a value type (the procedure address) as a first parameter, so how
else might I cast it? The solution may lie in the Marshal object,
but I cannot find it.

Heres the C++ code:
Code:
// Heres the delegate declaration
typedef ULONG (*GetAttachedDevicesProc) (ULONG* pDeviceCount, PTCHAR pBuffer, ULONG* pBufferSize);

// And the instance of that delegate
static GetAttachedDevicesProc	 gGetAttachedDevices;

// This is the tricky part, it casts the proc address to an actual delegate
gGetAttachedDevices = (GetAttachedDevicesProc) ::GetProcAddress (fgUSBLib, "PalmUsbGetAttachedDevices")

And the VB.NET code I have so far:
Code:
 The delegate:
Private Delegate Function GetAttachedDevicesDelegate(ByVal deviceCount As Integer, ByVal buffer As String, ByVal bufferSize As Integer) As Integer

 Getting the procedure address:
procAddress = New IntPtr(GetProcAddress(moduleHandle.ToInt32(), "PalmUsbGetAttachedDevices"))

 Now how do I make a new instance of GetAttachedDevicesDelegate based on the address?
 
Perhaps you should make the return type of GetProcAddress a Delegate type.
 
Oooh, good idea... unfortunately it didnt work. An error was thrown:
"System.ArgumentException - Function pointer was not created
by a Delegate."

So it looks like its closer than before...
 
Back
Top