Passing StringBuilder to PInvoke function

2020-02-15 01:51发布

问题:

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) 

回答1:

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.