Roy Osherove

View Original

Calling managed functions from unmanaged code

Our company has an internal mailing list of important and interesting things. Sometimes I'll grab some technical gems from there and post them for everyone's benefit.
For example:
 
Q:“I have a static method in managed code that I’d like to call from unmanaged code. Is there any recommended way of doing this?”
 
A:“This is easily doable...just create a delegate in managed code and pass it to unmanaged code.  It will turn into a callable function pointer on the unmanaged side.  Couple of things to be aware of:
 
1) Make sure the function pointer definition on the unmanaged side uses __stdcall.  Weird and bad things will happen if you try to use a different calling convention.
2) Make sure you keep the delegate alive on the managed side somehow (easiest way is to assign a static variable to it).  #1 mistake when doing this is letting the delegate go out of scope...the GC will collect it, and Bad Things(tm) will happen when the unmanaged side tries to invoke the function pointer.“