如何将托管对象发送到本机函数来使用它?
如何将托管对象发送到本机函数来使用它?
void managed_function()
{
Object^ obj = gcnew Object();
void* ptr = obj ??? // How to convert Managed object to void*?
unmanaged_function(ptr);
}
// The parameter type should be void* and I can not change the type.
// This function is native but it uses managed object. Because type of ptr could not be
// Object^ I called it "Unmanaged Function".
void unmanaged_function(void* ptr)
{
Object^ obj = ptr ??? // How to convert void* to Managed object?
obj->SomeManagedMethods();
}
How can I send a managed object to native function to use it?
void managed_function()
{
Object^ obj = gcnew Object();
void* ptr = obj ??? // How to convert Managed object to void*?
unmanaged_function(ptr);
}
// The parameter type should be void* and I can not change the type.
// This function is native but it uses managed object. Because type of ptr could not be
// Object^ I called it "Unmanaged Function".
void unmanaged_function(void* ptr)
{
Object^ obj = ptr ??? // How to convert void* to Managed object?
obj->SomeManagedMethods();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更干净、更好的方法是使用 gcroot 模板。
引用自 MSDN 如何:在本机类型中声明句柄:
您的示例代码适合使用
gcroot
(该代码使用 VS 2010 编译和运行):The cleaner and the better approach is to use gcroot template.
A quote from MSDN How to: Declare Handles in Native Types:
Your sample code adapted to use
gcroot
(the code compiles and runs using VS 2010):经过谷歌搜索、阅读 MSDN 并尝试一些代码后,我发现这个方法可以将托管对象传递给非托管函数。
这些方法展示了如何将 Object^ 转换为 void* 以及如何将 void* 转换为 Object^。
注意:如果“unmanaged_function”具有可变参数,则此方法将不起作用。
After googling, reading MSDN and try some codes, I found this method to pass a managed object to an unmanaged function.
These methods show how to convert Object^ to void* and convert void* to Object^.
Note: if "unmanaged_function" has variable arguments, this method won't work.