Passing a string variable as a link between C # dll and C ++ dll

I have C # dll and C ++ dll. I need to pass a string variable as a link from C # to C ++. My C ++ dll will populate the variable with data, and I will use it in C #, how can I do this. I tried using ref. But my C # dll threw an exception. "Attempting to read or write protected memory ... This often indicates that another memory is corrupt." Any idea on how this can be done

+3
source share
2 answers

As a general rule, you use StringBuilderfor reference or return values ​​and stringfor strings you don't need / need to be changed in the DLL.

StringBuilder LPTSTR, string LPCTSTR

#:

[DllImport("MyDll.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static void GetMyInfo(StringBuilder myName, out int myAge);

++:

__declspec(dllexport) void GetMyInfo(LPTSTR myName, int *age)
{
    *age = 29;
    _tcscpy(name, _T("Brian"));
}

# :

StringBuilder name = new StringBuilder(512);
int age; 
GetMyInfo(name, out age);
+2

StringBuilder # ++.

+1

Source: https://habr.com/ru/post/1736316/


All Articles