gpt4 book ai didi

c# - 将 StringBuilder 传递给 PInvoke 函数

转载 作者:行者123 更新时间:2023-11-30 20:11:50 25 4
gpt4 key购买 nike

在一篇标题为“从 C# 调用返回字符串的 C++ 方法”的帖子中

据说,要使以下 Pinvoke 正常工作,请将 C++ 签名更改为 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 转换为字符串。(但这是公认的答案)

我们不应该像下面这样使用 use IntPtr 吗?

extern "C" REGISTRATION_API void calculate(Intptr msg) 

最佳答案

寻找标记为“传递字符串”的部分,编码(marshal)拆收器有一些额外的智能来完成这个技巧。
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.

关于c# - 将 StringBuilder 传递给 PInvoke 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3203005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com