Marshal.GetFunctionPointerForDelegate

  • Thread starter Thread starter Lloyd Dupont
  • Start date Start date
L

Lloyd Dupont

I try to get a function pointer from a delegate with
Marshal.GetFunctionPointerForDelegate()

Doesn't works with Action<AManagedC++ type>
is there any reason why :-( ?!

--
Regards,
Lloyd Dupont

NovaMind development team
NovaMind Software
Mind Mapping Software
<www.nova-mind.com>
 
Lloyd Dupont said:
I try to get a function pointer from a delegate with
Marshal.GetFunctionPointerForDelegate()

Doesn't works with Action<AManagedC++ type>
is there any reason why :-( ?!

--
Regards,
Lloyd Dupont

NovaMind development team
NovaMind Software
Mind Mapping Software
<www.nova-mind.com>

You must use delegates with isomorphic types for
Marshal.GetFunctionPointerForDelete.
 
An isomorpic type is a type for that an equivalent type in both worlds
exist: Int32 is isomorphic because there is (are) 32 bit signed integer
types is the native world, too.

All in all I guess, this does probalby not really answer your initial
question about Marshal.GetFunctionPointerForDelegate, which is an
interesting one:

Marshal.GetFunctionPointerForDelegate creates a umnanaged/managed thunk that
forwards to a given delegate and returns a pointer to that thunk, so that
native functions can call this delegate.

Next question: What is an unmanaged/managed thunk?
An unmanaged/managed thunk is a runtime generated function, that can be
called from native code and forwards to a managed function. Thunks are
created in different scenarions:
* When a thunk is explicitly requested via
Marshal::GetFunctionPointerForDelegate
* When a P/Invoke function has a delegate as an argument
* When a manged function has a native calling convention (C++/CLI only)

Next question: Why should Marshal::GetFunctionPointerForDelegate be used?
Whenever you want to pass a pointer to a managed function to the native
world. This usually happens via a function pointer argument (e.g.
EnumWindows) or via a function pointer field of a native struct that is
passed as a method argument (WNDCLASS, RegisterWindowClass).

Next question: Do I really have to care about this?
In most cases not: Even if you have to call functions that expect a native
function pointer as an argument, there is another option: You can use a
delegate for your P/Invoke function, because the default P/Invoke marshaling
of delegates does the same as Marshal::GetFunctionPointerForDelegate would
do: It creates an unmanaged/managed thunk that forwards to a managed
function.

Maybe you would never have asked these questions and thought about something
different. But maybe someone found this useful.

Marcus Heege
DevelopMentor
 
Thanks Marcus for your long and detail answer.
Anyway finally I used Action<IntPtr>
and marshal the IntPtr <=> MyCustomeClass myself and it work beautifully...
 
Back
Top