Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
828 views
in Technique[技术] by (71.8m points)

c# - 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) 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...