C#中 - 如何转换对象要IntPtr的和后面? [英] C# - How To Convert Object To IntPtr And Back?
本文介绍了C#中 - 如何转换对象要IntPtr的和后面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从托管代码的对象传递给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.
如何转换对象
到的IntPtr
和后面?
How do I convert object
to IntPtr
and back ?
推荐答案
所以,如果我想通过WINAPI我使用的GCHandle 传递一个列表,我的回调函数p>
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
// back to object (in callback function):
GCHandle handle2 = (GCHandle) parameter;
List<string> list2 = (handle2.Target as List<string>);
list2.Add("hello world");
THX到的大卫·赫弗南
这篇关于C#中 - 如何转换对象要IntPtr的和后面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文