请帮忙,
my c++ function:
extern "C" REGISTRATION_API void calculate(char* msg)
{
//some calculation here
msg = "some text";
}
我的c#电话:
[DllImport("thecpp.dll")]
static extern void calculate(StringBuilder sMsg);
private void button4_Click(object sender, EventArgs e)
{
StringBuilder msg = new StringBuilder();
calculate(msg);
MessageBox.Show(msg.ToString());
}
无论我在msg中放入什么,stringbuilder总是空的?为什么?怎么了?有任何想法吗?请分享
答案 0 :(得分:2)
你是正确的,你应该string
用于LPCTSTR
缓冲区,StringBuilder
用于LPTSTR
缓冲区。
但您需要进行2次更改:
1)设置StringBuilder的容量
2)你应该在{缓冲区}中进行strcpy
,改变变量所持有的内存地址将不会像你现在那样做任何事情。您需要更改内存地址的内容。
所以你想要的C / C ++代码:
extern "C" REGISTRATION_API void calculate(LPSTR msg)
{
//Also consider refactoring this function to take in the buffer length
strcpy(msg, "some text");
}
并在C#中:
[DllImport("thecpp.dll", CharSet=CharSet.Ansi)]
static extern void calculate(StringBuilder sMsg);
private void button4_Click(object sender, EventArgs e)
{
StringBuilder msg = new StringBuilder(1024);
calculate(msg);
MessageBox.Show(msg.ToString());
}
注意:您确实应该将传入的缓冲区的长度传递给calculate函数。
答案 1 :(得分:-1)
我对语法有些模糊,但我相信你想要的东西:
[DllImport("thecpp.dll")] static extern void calculate([in, out] StringBuilder sMsg);