void* to Object^ in C++/CLI

时光怂恿深爱的人放手 提交于 2020-01-13 13:49:52

问题


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#.

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:

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:

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?


回答1:


Can you make it an IntPtr? What do you expect the client to do with the void*?




回答2:


If your managed code needs to see the data in the 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

If your managed code doesn't need to see the data in the 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



来源:https://stackoverflow.com/questions/1154929/void-to-object-in-c-cli

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!