Search This Blog

Tuesday, September 22, 2009

Calling MFC C++ API from C# (e.g. CString& param)

I have a C++ dll that written via MFC, I exposed an API from my dll, for this sample :
HRESULT __declspec( dllexport )RunTest(const CString& strIn, CString& strOut);

now i want to call it from my c# code, so i tried the next decalrtion:
[DllImport("myDLL.dll", CharSet = CharSet.Ansi)]
public static extern int RunTest(ref StringBuilder strIn, ref StringBuilder strOut);
the strings arrived to the c++ dlls , the problem was getting some unexpcted assertion in destructor and operator= of Cstring , any way as you know CString is a Class with buffer in it , and its looks like the marshal didn’t get well in runtime , I get the string but I get crashed from time to time.
so my workaround was as follow , in the C++ dll i created a new API method (wrapper one):

HRESULT __declspec( dllexport )RunTestManaged(LPCTSTR strXmlIn, LPTSTR strXmlOut, int buffCount)
//--------------------------------------------------------------------------
{
CString param1;
RunTest(strXmlIn,param1);
strncpy(strXmlOut,param1,buffCount);
return 0;
}

and in the C# code i created the next import section:
[DllImport("myDLL.dll", CharSet = CharSet.Ansi)]
public static extern int RunTestManaged(String strIn, ref StringBuilder strOut,int strOutBuffCount);


Make sure to allocate enough buffer in the string builder, this way the strIn and the strOut will be transferred perfectly.

Yaniv T

No comments: