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)?

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top