c# - 将 std::wstring 的内容从 C++ 返回到 C#

标签 c# c++ unicode interop

我有一个非托管 C++ DLL,我用一个简单的 C 接口(interface)包装了它,因此我可以从 C# 对其调用 PInvoke。这是 C 包装器中的示例方法:

const wchar_t* getMyString()
{
    // Assume that someWideString is a std::wstring that will remain
    // in memory for the life of the incoming calls.
    return someWideString.c_str();
}

这是我的 C# DLLImport 设置。

[DllImport( "my.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl )]
private static extern string GetMyString();

但是字符串没有正确编码,经常搞砸第一个字符或者有时显示一堆汉字。我已经记录了 C 端实现的输出,以确认 std::wstring 的格式正确。

我还尝试更改 DLLImport 以返回一个 IntPtr 并使用 Marshal.PtrToStringUni 使用包装方法进行转换,结果相同。

[DllImport( "my.dll", CallingConvention = CallingConvention.Cdecl )]
private static extern IntPtr GetMyString();
public string GetMyStringMarshal()
{
    return Marshal.PtrToStringUni( GetMyString() );
}

有什么想法吗?

用答案更新

所以如下所述,这实际上不是我的绑定(bind)问题,而是我的 wchar_t* 的生命周期问题。我的书面假设是错误的,someWideString 实际上是在我调用应用程序的其余部分期间被复制的。因此它只存在于堆栈中,在我的 C# 代码完成编码之前就被释放了。

正确的解决方案是按照 shf301 所述将指针传递到我的方法,或者确保我的 wchar_t* 引用在我的 C# 接口(interface)有时间复制它之前不会被移动/重新分配/销毁。

将 std::wstring 作为“const &std::wstring”返回到我的 C 层意味着我对 c_str() 的调用将返回一个引用,该引用不会立即在我的 C 方法范围之外解除分配.

调用 C# 代码然后需要使用 Marshal.PtrToStringUni() 将数据从引用复制到托管字符串中。

最佳答案

由于 Hans Passant's answer 中提到的原因,您将不得不重写 getMyString 函数.

您需要让 C# 代码将缓冲区传递给您的 C++ 代码。这样,您的代码(好的,CLR 编码器)控制缓冲区的生命周期,并且您不会陷入任何未定义的行为。

下面是一个实现:

C++

void getMyString(wchar_t *str, int len)
{
    wcscpy_s(str, len, someWideString.c_str());
}

C#

[DllImport( "my.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode )]
private static extern void GetMyString(StringBuffer str, int len);
public string GetMyStringMarshal()
{
    StringBuffer buffer = new StringBuffer(255);
    GetMyString(buffer, buffer.Capacity);
    return buffer.ToString();
}

关于c# - 将 std::wstring 的内容从 C++ 返回到 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7051097/

相关文章:

c++ - 使用 unique_ptr 描述意图

c++ - std::map 不插入空?

ruby - 如何将 unicode 字符串转换为其在 Ruby 中的符号字符?

c# - 将字符串转换或显示为货币

c# - Java 似乎支持 long 类型的可变字段,而 C# 不支持 - 这背后的原因是什么?

c++ - 为什么我的数字在我的猜数字游戏中计算不正确?

c++ - Unicode 文本在编辑框中显示为问号,即使我使用 SetWindowTextW()

javascript - 特殊字符 '\u0098' 使用 charCodeAt() 读取为 '\u02dc'

c# - 如何检查页面是否作为提交表单或其他方式的结果显示

c# - 如何从 PDF 中提取文本并解码字符?