Please help,
my c++ function:
extern "C" REGISTRATION_API void calculate(char* msg)
{
//开发者_如何转开发some calculation here
msg = "some text";
}
my c# call:
[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());
}
No matter what i put in msg, the stringbuilder is always empty? why? whats wrong? any ideas? please share
You are correct that you should use string
for LPCTSTR
buffers and StringBuilder
for LPTSTR
buffers.
But you need 2 changes:
1) Set the capacity on your StringBuilder
2) You should be doing strcpy
into that buffer, changing what memory address that variable holds won't do anything as you have it now. You need to change what is at the memory address.
So you want in your C/C++ code:
extern "C" REGISTRATION_API void calculate(LPSTR msg)
{
//Also consider refactoring this function to take in the buffer length
strcpy(msg, "some text");
}
and in 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());
}
Note: You really should pass in the length of the buffer that you are passing in to the calculate function as well.
I'm a bit hazy on the syntax, but I believe you want something like:
[DllImport("thecpp.dll")] static extern void calculate([in, out] StringBuilder sMsg);
精彩评论