Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing StringBuilder to PInvoke function

In one of the post Titled "Call a c++ method that returns a string, from c#"

Its said that , to make the following Pinvoke to work change the C++ signature to as

extern "C" REGISTRATION_API void calculate(LPSTR msg) 

C++ code

extern "C" REGISTRATION_API void calculate(char* msg) 

C# code

[DllImport("thecpp.dll", CharSet=CharSet.Ansi)] 
static extern void calculate(StringBuilder sMsg); 

How can stringBuilder which is a class ,convertd to long ptr to string .(but this is the accepted answer)

Shouldnt we use use IntPtr as below ?

extern "C" REGISTRATION_API void calculate(Intptr msg) 
like image 382
Somaraj Avatar asked Feb 27 '23 17:02

Somaraj


1 Answers

Look for the section marked "Passing Strings", the marshaler has got some added smarts to do this trick.
http://msdn.microsoft.com/en-us/library/aa446536.aspx

To solve this problem (since many of the Win32 APIs expect string buffers) in the full .NET Framework, you can, instead, pass a System.Text.StringBuilder object; a pointer will be passed by the marshaler into the unmanaged function that can be manipulated. The only caveat is that the StringBuilder must be allocated enough space for the return value, or the text will overflow, causing an exception to be thrown by P/Invoke.

like image 180
Gishu Avatar answered Mar 01 '23 11:03

Gishu