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

前端 未结 3 1010
误落风尘
误落风尘 2020-12-05 07:56

I have run in to this problem of converting a C++/CLI pointer to a native C++ pointer. Heres the background: I\'m writing a windows forms application using C++/CLI. The appl

3条回答
  •  春和景丽
    2020-12-05 08:54

    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 ^bytes = u8->GetBytes( s );
        pin_ptr 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 pinnedPtr = &provider;
    CoCreateInstance(rclsid, pUnkOuter, dwClsContext, riid, (void**)pinnedPtr); 
    

    and see whether that works.

提交回复
热议问题