繁体   English   中英

将字符串从C ++传递到C#

[英]Passing string from c++ to c#

我正在尝试将字符串从C ++传递给C#。

C++:
extern "C" __declspec(dllexport) void GetSurfaceName(wchar_t* o_name);

void GetSurfaceName(wchar_t* o_name)
{
  swprintf(o_name, 20, L"Surface name");
}

C#:
[DllImport("SurfaceReader.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern void GetSurfaceName(StringBuilder o_name);

StringBuilder name = new StringBuilder(20);
GetSurfaceName(name);

但是只传递第一个符号:name [0] =='S'。 其他符号为空。 你能告诉我这里有什么问题吗?

谢谢振亚

您忘记告诉pinvoke编组该函数正在使用Unicode字符串。 默认值为CharSet.Ansi,您需要显式使用CharSet.Unicode。 固定:

[DllImport("SurfaceReader.dll", 
           CallingConvention = CallingConvention.Cdecl, 
           CharSet = CharSet.Unicode)]
private static extern void GetSurfaceName(StringBuilder o_name);

现在,您将获得一个“ S”,因为“ S”的utf-16编码值看起来像一个带有一个字符的C字符串。

通常应避免使用魔术数字,例如“ 20”。 只需添加一个参数,说明字符串缓冲区的长度。 这样,您将永远不会意外损坏GC堆。 传递StringBuilder.Capacity。 并为该函数提供可以指示成功的返回值,这样您就不会忽略缓冲区太小的情况。

我不确定,但是我不是使用StringBuilder,而是将C#char(wchar)数组传递给C ++,填充它,然后在C#中对该数组进行操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM