开发者

Passing StringBuilder to PInvoke function

开发者 https://www.devze.com 2023-01-06 15:25 出处:网络
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 workchange the C++ signature to as

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) 
开发者_如何学JAVA

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) 


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消