Suppose you have a managed class that converts a delegate member to a native function pointer and hands it to native code. Assume that the class/delegate stays in scope and does not change for the lifetime of the native code (so that will not be obviously destroyed by the GC). What other problems should one be aware of in this situation? For example, is it possible for the GC to move the delegate or the actual method the delegate refers to and leave your native code with an access violation?
It seems that it's possible to pin the memory location of the delegate/function, but this obstructs a major advantage of the .NET GC: compacting.
Once a GC sweep is done, every object is relocated in memory to be contiguous. This makes both access and allocation faster that it would be if the heap were fragmented. If you have to pin an object in place in the heap, the GC would have to work around it and if it were done multiple times, it could lead to some nontrivial heap fragmentation. (By the way, this is addressed with GCHandle in the article linked by Ron Warholic. I'm not sure if that is available outside managed C++.)
I'm not much of a .Net expert, but I think you should take a look here : Marshal Callbacks and Delegates Using C++ Interop.
Notice that is it possible, but not necessary, to pin the delegate using pin_ptr to prevent it from being re-located or disposed of by the garbage collector. Protection from premature garbage collection is needed, but pinning provides more protection than is necessary, as it prevents collection but also prevents relocation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With