C# - 如何将对象转换为 IntPtr 并返回? [英] C# - How To Convert Object To IntPtr And Back?
问题描述
我想将对象从托管代码传递到 WinApi 函数作为 IntPtr
.它会将此对象作为 IntPtr
传递回托管代码中的回调函数.它不是结构,而是类的实例.
I want to pass an object from managed code to a WinApi function as IntPtr
. It will pass this object back to my callback function in managed code as IntPtr
. It's not a structure, it's an instance of a class.
如何将 object
转换为 IntPtr
并返回?
How do I convert object
to IntPtr
and back ?
推荐答案
所以如果我想通过 WinApi 将列表传递给我的回调函数,我使用 GCHandle
So if I want to pass a list to my callback function through WinApi I use 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");
感谢大卫·赫弗南
如评论中所述,您需要在使用后释放手柄.我也使用了铸造.使用静态方法 GCHandle.ToIntPtr(handle1)
和 GCHandle.FromIntPtr(parameter)
像 这里.我还没有验证过.
As noted in the comments, you need to free the handle after use. Also I used casting. It might be wise to use the static methods GCHandle.ToIntPtr(handle1)
and GCHandle.FromIntPtr(parameter)
like here. I haven't verified that.
这篇关于C# - 如何将对象转换为 IntPtr 并返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!