将StringBuilder传递给PInvoke函数 [英] Passing StringBuilder to PInvoke function
问题描述
标题为从c#调用返回字符串的c ++方法"的帖子之一
In one of the post Titled "Call a c++ method that returns a string, from c#"
它表示要使以下Pinvoke正常工作,请将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 ++代码
extern "C" REGISTRATION_API void calculate(char* msg)
C#代码
[DllImport("thecpp.dll", CharSet=CharSet.Ansi)]
static extern void calculate(StringBuilder sMsg);
如何将作为类的stringBuilder转换为long ptr转换为string.(但这是公认的答案)
How can stringBuilder which is a class ,convertd to long ptr to string .(but this is the accepted answer)
我们是否应该按如下方式使用IntPtr?
Shouldnt we use use IntPtr as below ?
extern "C" REGISTRATION_API void calculate(Intptr msg)
推荐答案
查找标记为传递字符串"的部分,封送邮件处理程序添加了一些聪明的人来执行此技巧.
http://msdn.microsoft.com/en-us/library/aa446536.aspx
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
要解决此问题(因为许多 Win32 API需要字符串缓冲区) 在完整的.NET Framework中,您可以 相反,传递一个 System.Text.StringBuilder对象;一种 指针将通过 封送处理程序进入非托管功能 可以操纵的唯一的 需要注意的是,StringBuilder必须 被分配足够的空间 返回值,否则文本将 溢出,导致出现异常 由P/Invoke抛出.
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.
这篇关于将StringBuilder传递给PInvoke函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!