是否需要GCHandle.Alloc才能允许非托管函数存储托管委托?

 收藏

I've DllImported a C function that wants to store a function pointer to my managed method MyFunction

public void MyFunction(int a) { ... }

我可以这样声明:

public delegate void MyFunctionDelegate(int a);
[DllImport("example.dll"]
public static extern void RegisterFunction(MyFunctionDelegate funPointer);

并像这样调用它

RegisterFunction(new MyFunctionDelegate(MyFunction));

但这是行不通的,因为MSDN文档指出,如果非托管函数正在存储指针,则必须防止收集委托。

那么在非托管功能需要它保持生命的持续时间内,仅存储对委托的引用就足够了吗?

_myFunctionDelegate = new MyFunctionDelegate(MyFunction); // member variable
RegisterFunction(_myFunctionDelegate);

Or do I also need a GCHandle on it?

_gcHandle = GCHandle.Alloc(_myFunctionDelegate, GCHandleType.Pinned); // is pinned required?
RegisterFunction(_myFunctionDelegate);
回复