I have a c# dll and a c++ dll . I need to pass a string variable as reference from c# to c++ . My c++ dll will fill the variable with data and I will be using it in C# how can I do this. I tried using ref. But my c# dll throwed exception . "Attempted to read or write protected memory. ... This is often an indication that other memory is corrupt". Any idea on how this can be done
2 Answers
As a general rule you use StringBuilder for reference or return values and string for strings you don't want/need to change in the DLL.
StringBuilder corresponds to LPTSTR and string corresponds to LPCTSTR
C# function import:
[DllImport("MyDll.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static void GetMyInfo(StringBuilder myName, out int myAge);
C++ code:
__declspec(dllexport) void GetMyInfo(LPTSTR myName, int *age)
{
*age = 29;
_tcscpy(name, _T("Brian"));
}
C# code to call the function:
StringBuilder name = new StringBuilder(512);
int age;
GetMyInfo(name, out age);
4 Comments
Ben Voigt
And since LPTSTR and LPCTSTR become meaningless at a compilation boundary, use the CharSet attribute to let .NET know whether to use LP(C)STR or LP(C)WSTR
Brian R. Bondy
@Ben: Yes of course, you can use the wide char version if you want or set the C# code to auto charset.
subbu
I used the above code but I am getting some junk values instead of Brian
Brian R. Bondy
In the above examples try changing all of the C++ LPTSTR to LPSTR and all of the LPCTSTR TO LPCSTR. Change _tcscpy to strcpy and remove the _T around the string. Also in the C# function prototype change CharSet = CharSet.Auto to CharSet.Ansi.