【发布时间】:2011-08-01 19:15:58
【问题描述】:
这是一个与this SO post 类似的问题,我一直无法用它来解决我的问题。我在这里包含了一些代码,希望能帮助某人将其他帖子所传达的信息带回家。
我想编写一个 CLI/C++ 方法,该方法可以将 void 指针作为参数并返回它指向的托管对象(我知道其类型)。我有一个托管结构:
public ref struct ManagedStruct { double a; double b;};
我正在尝试编写的方法,它将指向托管结构的 void 指针作为参数并返回该结构。
ManagedStruct^ VoidPointerToObject(void* data)
{
Object^ result = Marshal::PtrToStructure(IntPtr(data), Object::typeid);
return (ManagedStruct^)result;
}
这里调用方法:
int main(array<System::String ^> ^args)
{
// The instance of the managed type is created:
ManagedStruct^ myData = gcnew ManagedStruct();
myData->a = 1; myData->b = 2;
// Suppose there was a void pointer that pointed to this managed struct
void* voidPtr = &myData;
//A method to return the original struct from the void pointer
Object^ result = VoidPointerToObject(voidPtr);
return 0;
}
它在调用PtrToStructure 时在VoidPointerToObject 方法中崩溃,并出现错误:指定的结构必须是blittable 或具有布局信息
我知道这样做很奇怪,但这种情况我已经遇到过几次了,尤其是当非托管代码对托管代码进行回调并将 void* 作为参数传递时。
【问题讨论】:
标签: pointers c++-cli command-line-interface