tags:

views:

70

answers:

2

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

A: 

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);
James Curran
nope, i added the in/out, still no answer from the stringbuilder
Zee99
+2  A: 

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.

Brian R. Bondy
can u please give me an example
Zee99
@Zee99: Try what I gave you above.
Brian R. Bondy
Thanks, did it.
Zee99
The StringBuilder constructor call is wrong. That should be 666.
Hans Passant