I assume the problem is that you are allocating memory using the C ++ runtime manager, but then the C # marshaller tries to free it. This will not work. You need to select and release the allocated allocator.
The best way I know to solve your problem is to marshal with BSTR
. This uses a COM distributor, which is happy to share between native and managed modules.
#include <comutil.h> BSTR cppReturnSomeText() { UnicodeString usText("Some Text Here"); std::wstring result = ECUtilsICU::UniCodeStringToWString(usText); return ::SysAllocString(result.c_str()); }
On the C # side, you do the following:
[DllImport(MY_DLL_NAME, CallingConvention=CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.BStr)] private static extern string cppReturnSomeText();
Another advantage of this is that your code is now thread safe because you no longer need a global variable.
source share