我想将托管代码中的对象作为 IntPtr
传递给 WinApi 函数。它会将此对象作为 IntPtr
传递回托管代码中的回调函数。它不是结构,而是类的实例。
如何将 object
转换为 IntPtr
并返回?
最佳答案
因此,如果我想通过 WinApi 将列表传递给我的回调函数,我会使用 GCHandle
// object to IntPtr (before calling WinApi):
List<string> list1 = new List<string>();
GCHandle handle1 = GCHandle.Alloc(list1);
IntPtr parameter = (IntPtr) handle1;
// call WinAPi and pass the parameter here
// then free the handle when not needed:
handle1.Free();
// back to object (in callback function):
GCHandle handle2 = (GCHandle) parameter;
List<string> list2 = (handle2.Target as List<string>);
list2.Add("hello world");
编辑:如评论中所述,您需要在使用后释放 handle 。我也使用了类型转换。使用静态方法 GCHandle.ToIntPtr(handle1)
和 GCHandle.FromIntPtr(parameter)
可能是明智的,比如 here .我还没有证实这一点。
关于C# - 如何将对象转换为 IntPtr 并返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17339928/