作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何将托管对象发送到 native 函数来使用它?
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();
}
最佳答案
更干净、更好的方法是使用 gcroot模板。
引自 MSDN How to: Declare Handles in Native Types :
The gcroot template is implemented using the facilities of the value class System::Runtime::InteropServices::GCHandle, which provides "handles" into the garbage-collected heap. Note that the handles themselves are not garbage collected and are freed when no longer in use by the destructor in the gcroot class (this destructor cannot be called manually). If you instantiate a gcroot object on the native heap, you must call delete on that resource.
您的示例代码适用于使用 gcroot
(代码使用 VS 2010 编译和运行):
using namespace System;
using namespace System::Runtime::InteropServices;
public ref class SomeManagedObject
{
public:
String^ data;
SomeManagedObject()
{
data = "Initial Data";
}
void SomeManagedMethods()
{
data = "Changed Data";
}
};
void unmanaged_function(void* ptr)
{
gcroot<SomeManagedObject^>& obj = *((gcroot<SomeManagedObject^>*)ptr);
obj->SomeManagedMethods();
}
void managed_function()
{
// gcroot handles all allocations/deallocation and convertions
gcroot<SomeManagedObject^>* pObj = new gcroot<SomeManagedObject^>();
*pObj = gcnew SomeManagedObject();
unmanaged_function(pObj);
delete pObj;
}
关于.net - 如何将托管对象发送到 native 函数来使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7371775/
我是一名优秀的程序员,十分优秀!