4

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

0

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

4 Comments

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: Yes of course, you can use the wide char version if you want or set the C# code to auto charset.
I used the above code but I am getting some junk values instead of Brian
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.
1

Pass a fixed size StringBuilder from C# to C++.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.