// --------------------------- C# Code ------------------------------
[DllImport("MarshallStringsWin32.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
extern static void PassStringOut([MarshalAs(UnmanagedType.BStr)] out String str);
[DllImport("MarshallStringsWin32.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
extern static void FreeString([MarshalAs(UnmanagedType.BStr)] String str);
static void Main(string[] args)
{
String str;
PassStringOut(out str);
FreeString(str);
}
// --------------------------- C+ Code ------------------------------
void PassStringOut(__out BSTR* str)
{
const std::string stdStr = "The quick brown fox jumps over the lazy dog";
_bstr_t bstrStr = stdStr.c_str();
*str = bstrStr.copy();
}
void FreeString(BSTR str)
{
SysFreeString(str);
}
The value of 'str' pointer in PassStringOut() and FreeString() are different, and I am getting a heap corruption error when calling SysFreeString(). Should I pass 'str' by reference to FreeString()? If so, what is the syntax I should use in C# and C++?