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
Asked
Active
Viewed 3,601 times
2 Answers
3
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);

Brian R. Bondy
- 339,232
- 124
- 596
- 636
-
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 – Ben Voigt Mar 10 '10 at 14:25
-
@Ben: Yes of course, you can use the wide char version if you want or set the C# code to auto charset. – Brian R. Bondy Mar 10 '10 at 14:33
-
I used the above code but I am getting some junk values instead of Brian – subbu Mar 11 '10 at 07:24
-
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. – Brian R. Bondy Mar 11 '10 at 13:55