开发者

Passing a string variable as a ref between a c# dll and c++ dll

开发者 https://www.devze.com 2022-12-22 07:06 出处:网络
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

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 of开发者_开发问答ten an indication that other memory is corrupt". Any idea on how this can be done


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);


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

0

精彩评论

暂无评论...
验证码 换一张
取 消