Personally, I think this is easiest to do with BSTR and thus avoid the need to export deallocator.
C ++
BSTR ANSItoBSTR(const char* input) { BSTR result = NULL; int lenA = lstrlenA(input); int lenW = ::MultiByteToWideChar(CP_ACP, 0, input, lenA, NULL, 0); if (lenW > 0) { result = ::SysAllocStringLen(0, lenW); ::MultiByteToWideChar(CP_ACP, 0, input, lenA, result, lenW); } return result; } BSTR __stdcall getString() { return ANSItoBSTR("Hello world"); }
Of course, if you work with Unicode strings, this is even easier.
BSTR __stdcall getString() { return ::SysAllocString(L"Hello world"); }
FROM#
[DllImport(@"test.dll")] [return: MarshalAs(UnmanagedType.BStr)] private static extern string getString();
And on the C # side it is. You just call getString() , and it returns a .net string , and you don't need to march or call a deactivator.
source share