I love three things in the world,sun,moon,and you. sun for morning, moon for night and you forever.

0%

C++生成动态库返回字符串给C#调用

【背景】

C#调用C++生成的DLL,C#调用函数,接收C++返回的字符串

【C++】

1
2
3
4
5
6
7
8
static char buff[20]; //存储返回的字符串

char* testString()
{
string tmp = "hello world";
strcpy_s(buff, tmp.c_str());
return buff;
}

【C#】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//导入动态库
[DllImport("xxxx.dll", EntryPoint = "testString", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr testString();

//---------------------分割线------------------------------

//函数调用
IntPtr intPtr = testString();
string str = Marshal.PtrToStringAnsi(intPtr);
//Console.WriteLine(str);
MessageBox.Show( str );


//第二种方法 加上判断返回的字符串是否为空
IntPtr intPtr = testString();
string str = "";
str = Marshal.PtrToStringAnsi(intPtr);
if (string.IsNullOrEmpty(str))
{
MessageBox.Show("fail");
}else
{
MessageBox.Show(str);
}

以上就是我的方法,实测可以接收到字符串数据。

-------------本文结束 感谢您的阅读-------------