C# - 如何将对象转换为 IntPtr 并返回?

标签 c# winapi callback marshalling intptr

我想将托管代码中的对象作为 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");

感谢 David Heffernan

编辑:如评论中所述,您需要在使用后释放 handle 。我也使用了类型转换。使用静态方法 GCHandle.ToIntPtr(handle1)GCHandle.FromIntPtr(parameter) 可能是明智的,比如 here .我还没有证实这一点。

关于C# - 如何将对象转换为 IntPtr 并返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17339928/

相关文章:

c# - 升级到 .NET Core 1.1.1 后,ASP.NET Core MVC 应用程序洞察力停止工作

c# - 截图并以表格形式显示

c# - 如何从另一个应用程序的文本框中获取插入符号位置? (不是坐标,而是文本框内的实际索引)

angular - fullcalendar Angular - 更新 eventDrop 和 eventResize 上的数据库

c# - 将 protobuf-net 流转换为 base64 是否会破坏 protobuf 的性能和大小优势?

c# - 在执行时使用 MVC 3 和 jQuery Validator 添加验证

c# - 如何阻止双击 Windows 窗体中覆盖的 WndProc 函数?

c++ - 为什么单向链表的 Next() 操作要用临界区保护?

delphi - 如何使用此 CustomSort 函数对 ListView 进行排序?

javascript如何在回调函数中获取this.variable