Question

I have three unmanaged dll functions:

void Init(){}
void Run(){}
void Done(){}

They work with the same managed object. Init() function inits the object, Run() uses it and Done() clears it.

My main question is: Is it necessary to use GCHandle.Alloc(managedObject, GCHandleType.Pinned) for such object (to pin it)?

Was it helpful?

Solution

You need to pin your object, whenever you pass it to unmanaged code, which stores it and tries to access it later. So if you pass the object to your Init function, which stores its adress to access it later when the Run function gets called, you have to pinn it because the adress can change between the call to the Init and the Run function.

All in all: The GC moves around managed objects. So if unmanaged code tries to access your memory you better pin it. Otherwise the unmanaged code may access something completely different which causes undef. behaviour.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top