I am working on wrapping a large number of .h and .lib files from native C++ to Managed C++ for eventual use as a referenced .dll in C#.
我正在努力将大量的.h和.lib文件从本机C ++包装到托管C ++,最终用作C#中引用的.dll。
Some of the native C++ functions have a return type of void*. I am not sure how to handle this when I pass back the value to my calling code. For instance: if a C# app calls my dll wrapper, what do I return from the native call:
某些本机C ++函数的返回类型为void *。当我将值传回给我的调用代码时,我不确定如何处理这个问题。例如:如果C#app调用我的dll包装器,我将从本机调用返回什么:
void* start(ThreadFunc,void *, unsigned *);
I am currently attempting to box the return in a generic System::Object^ with no luck. This is the call in the wrapper:
我目前正试图在通用的System :: Object中包装返回,但没有运气。这是包装器中的调用:
m_NativeThread->start(cb,
GCHandle::ToIntPtr(GCHandle::Alloc(o)).ToPointer(),
static_cast<unsigned int*>(GCHandle::ToIntPtr(GCHandle::Alloc(u)).ToPointer())));
Can anyone offer a solution?
有人能提供解决方案吗?
2 个解决方案
#1
Can you make it an IntPtr? What do you expect the client to do with the void*?
你能把它变成IntPtr吗?您希望客户对void *做什么?
#2
If your managed code needs to see the data in the void*:
如果您的托管代码需要查看void *中的数据:
You can't cast a void* to unmanaged memory to a managed object reference. To turn this into managed memory, you'd have to use Marshal.Copy() or Marshal.PtrToStructure(). That will of course only work if you know the type of the data that the void* points to. source
您不能将void *转换为非托管内存到托管对象引用。要将其转换为托管内存,您必须使用Marshal.Copy()或Marshal.PtrToStructure()。当然,只有当您知道void *指向的数据类型时,这才有效。资源
If your managed code doesn't need to see the data in the void*:
如果您的托管代码不需要查看void *中的数据:
Store it in an IntPtr if your managed code doesn't need to see what it is and just passes it back into the unmanaged code later on. source
如果您的托管代码不需要查看它是什么,并将其稍后传回非托管代码,则将其存储在IntPtr中。资源
#1
Can you make it an IntPtr? What do you expect the client to do with the void*?
你能把它变成IntPtr吗?您希望客户对void *做什么?
#2
If your managed code needs to see the data in the void*:
如果您的托管代码需要查看void *中的数据:
You can't cast a void* to unmanaged memory to a managed object reference. To turn this into managed memory, you'd have to use Marshal.Copy() or Marshal.PtrToStructure(). That will of course only work if you know the type of the data that the void* points to. source
您不能将void *转换为非托管内存到托管对象引用。要将其转换为托管内存,您必须使用Marshal.Copy()或Marshal.PtrToStructure()。当然,只有当您知道void *指向的数据类型时,这才有效。资源
If your managed code doesn't need to see the data in the void*:
如果您的托管代码不需要查看void *中的数据:
Store it in an IntPtr if your managed code doesn't need to see what it is and just passes it back into the unmanaged code later on. source
如果您的托管代码不需要查看它是什么,并将其稍后传回非托管代码,则将其存储在IntPtr中。资源