将非托管 unicode 字符串编组到 .net。高位字符替换为问号
这可能是也可能不是 SWIG 问题。
我试图按值从 C++ 函数返回 std::wstring 到 C#。返回的字符串混合了普通的旧英语字符和希伯来语字符。英语字符表现良好,但希伯来语字符在某些时候会转换为问号符号。
我正在使用 SWIG 生成编组代码。使用调试器单步调试所有内容,得到以下 SWIG 代码......
static string CreateWString([MarshalAs(UnmanagedType.LPWStr)]IntPtr cString) {
string str = System.Runtime.InteropServices.Marshal.PtrToStringUni(cString);
return str;
}
此时 str 看起来很完美。
接下来,它返回到 SWIG 生成的 C++ 代码,该代码将 str 作为 void* 返回。
然后 void* 在调用代码中再次变成 .net 字符串。在调用代码中,所有希伯来语字符都是 ?标记。
有什么想法造成这种情况吗?
编辑:
更多信息
CreateWString 返回到 C++ 调用者后,您可以看到调试器中的指针看起来是带有 ? 的 ANSI 字符串。里面有标记。因此,.net 似乎在字符串返回给调用者之前对其执行某种转换。听起来对吗?我怎样才能控制它?
编辑2: 看来我需要对返回类型 CreateWString 执行 MarshallAs 来阻止 .net 转换为 TCHAR 类型(?)
This may or may not be a SWIG question.
I am trying to return a std::wstring by value from a C++ function to C#. The returned string has a mixture of plain old English chars and Hebrew chars. The English chars come through fine, but the Hebrew chars are being converted to the question mark symbol at some point.
I am using SWIG to generate the marshalling code. Stepping through it all with a debugger, it gets to the following SWIG code...
static string CreateWString([MarshalAs(UnmanagedType.LPWStr)]IntPtr cString) {
string str = System.Runtime.InteropServices.Marshal.PtrToStringUni(cString);
return str;
}
At this point str looks perfect.
Next this is returned to the SWIG-generated C++ code which returns the str as a void*.
Then the void* becomes a .net string again in the calling code. In the calling code, all the hebrew chars are ? marks.
Any ideas what's causing this?
Edit:
Further information
As soon as CreateWString returns to the C++ caller you can see the pointer in the debugger looks to be an ANSI string with ? marks in it. So it seems that .net is performing some sort of conversion on the string before it returns to the caller. Does that sound right? How can I control that?
Edit 2:
It seems I need to do MarshallAs on the return type CreateWString to stop .net from converting to a TCHAR type (?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将
CreateWString
定义修改为:请参阅 MarshalAsAttribute 文档。
Modify the
CreateWString
definition to:See the examples in the MarshalAsAttribute documentation.