简体   繁体   中英

How to free an unmanaged memory that was allocated by marshalling from C# to C++

C++ code calls C# method which returns string. How I should free the allocated unmanaged memory in C++? Should I use free() or delete?

C#:

[Guid("52E4971F-E075-41BA-A84F-B6BE8BD66A21")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface ISomeInterface
{
     [return: MarshalAs(UnmanagedType.LPWStr)]
     string SomeMethod([MarshalAs(UnmanagedType.LPWStr)] string text);
}

C++:

class SomeClass
{
    virtual int32_t __stdcall _someMethod(const char16_t *text, char16_t **r) = 0;

    char16_t * someMethod(const char16_t *text)
        {
            char16_t * result;
            _someMethod(text, &result);
            return result; // how to correct release this memory?
        }
}

The solution works on Windows as well as on Linux.

Assuming your calling an object that has a COM signature like this:

interface MyObj
{
   HRESULT __stdcall MethodOrProp([out, retval] BSTR* SomeStringReturned);
};

Then, you call SysFreeString.

MyObj* pObj;
// ....

BSTR bstr = NULL;
HRESULT hr = pObj->MethodOrProp(&bstr);
if (SUCCEEDED(hr))
{
   // ... do junk with string ...
   SysFreeString(bstr);
}

But, if you are using Visual Studio, then don't worry about it and use CComBSTR. It will do the cleanup for you in its destructor.

CComBSTR ccbString = NULL;
HRESULT hr = pObj->MethodOrProp(&ccbString);
if (SUCCEEDED(hr))
{
   // ... do junk with string ...
}
// some time at end of scope, destructor of ccbString will clean it up

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM