Convert from C++/CLI pointer to native C++ pointer

橙三吉。 提交于 2019-11-27 20:12:12

I believe you have to mark the pointer as 'pinned' (in the managed code) and then copy the bytes over to some unmanaged memory region, and then use the pointer to that. For instance, here's a piece of code I once got somewhere which converts a pointer to a managed System::String to an UTF-8 encoded unmanaged std::string:

std::string managedStringToStlString( System::String ^s )
{
    Encoding ^u8 = Encoding::UTF8;
    array<unsigned char> ^bytes = u8->GetBytes( s );
    pin_ptr<unsigned char> pinnedPtr = &bytes[0];
    return string( (char*)pinnedPtr );
}

Note how I've got to get a 'pinned' pointer to the bytes array returned by the GetBytes() function, and then cast that to char* before passing it to the std::string constructor. I believe this is necessary to avoid that the managed memory subsystem moves the bytes array around in memory while I'm copying the bytes into the STL string.

In your case, try replacing

CoCreateInstance(rclsid, pUnkOuter, dwClsContext, riid, (void**)(&provider)); 

with

pin_ptr<void *> pinnedPtr = &provider;
CoCreateInstance(rclsid, pUnkOuter, dwClsContext, riid, (void**)pinnedPtr); 

and see whether that works.

It's quite some time that I used C++/CLI, but I think you have to pin the pointer.

Is the memory pointed to expected to be valid beyond the call to CoCreateInstance()?

As Frerich and Achim alluded to, you can get a raw pointer to the memory, without fear of the memory being relocated, by "pinning" it and getting an interior pointer. You usually do this with the pin_ptr template (see Frerich post for an example).

However, pin_ptr is deliberately only usable on the stack. You cannot use it as member variable or a global, and you can't pass it as an argument or return value. The memory is unpinned when it leaves scope.

So if the memory is only required to be valid during the call to CoCreateInstance() then pin_ptr is the way to go. If not then you will have to take a copy of the memory and pass that on to CoCreateInstance()

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