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

时间:2011-08-13 14:39:53

标签: c# c++ unicode interop

我有一个非托管的C ++ DLL,我用一个简单的C接口包装,所以我可以从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() );
}

有什么想法吗?

使用答案更新

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

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

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

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

2 个答案:

答案 0 :(得分:6)

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

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

以下是一项实施:

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();
}

答案 1 :(得分:4)

您需要为返回值指定MarshalAs属性:

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

确保函数确实是cdecl,并且在函数返回时不会销毁wstring对象。