gpt4 book ai didi

c# - 如何通过 p/invoke 将 C# 字符串传递给 linux/glibc wchar_t * 参数?

转载 作者:太空宇宙 更新时间:2023-11-04 04:32:21 25 4
gpt4 key购买 nike

我有一个 .NET Core 2.2 C# 应用程序,它使用 DllImport 引入 CentOS 7.5 上的 native 共享库(使用 gcc 编译的 C++ extern“C”接口(interface))。 C++ 库中的函数需要 wchar_t * 参数,但这些参数似乎被编码为 UTF16 字符串,而不是 gcc/glibc 中实现的 UTF32 字符串。这是(我的)程序员错误还是应该向 .NET Core 团队提出?

这是我尝试调用的高度复杂的方法:

void wchar_tTest(const wchar_t *arg1, const wchar_t *arg2)
{
std::wcout << L"wchar_tTest: arg1: " << arg1 << L", arg2: " << arg2 << std::endl;

char *s = (char *)arg1;
for (int i = 0; i < 12; i++)
{
printf("%d: %c\n", i, s[i]);
}
}

我尝试在托管端的 DllImport 上使用 MarshalAs(UnmanagedType.LPWSTR) 和/或 CharSet.Unicode 但无济于事。这两者都会产生相似的结果:

[DllImport("cover", EntryPoint = "wchar_tTest", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
public static extern void LPWSTRStringTest([MarshalAs(UnmanagedType.LPWStr)] string arg1, [MarshalAs(UnmanagedType.LPWStr)] string arg2);

[DllImport("cover", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
public static extern void wchar_tTest(string arg1, string arg2);

调用如下所示(stringTest() 是一个类似的调用,但调用的是带有 char * 参数的函数):

string arg1 = "Hello!";
string arg2 = "Goodbye!";

stringTest(arg1, arg2);

wchar_tTest(arg1, arg2);

LPWSTRStringTest(arg1, arg2);

当参数通过wcout转储出来时,Hello!变成HloGoodbye!变成Gobe。当您逐个字符浏览时,输出看起来可疑地像 UTF16...看起来 wchar_t * 跳过了所有其他 UTF16 字符(我假设将其视为 UTF32 字符串)。

wchar_tTest: arg1: Hlo, arg2: Gobe
0: H
1:
2: e
3:
4: l
5:
6: l
7:
8: o
9:
10: !
11:

有没有办法在不进行自定义编码的情况下解决此问题?毕竟我读过之后,这似乎应该是一个简单的任务,但我在这里。

最佳答案

文本被编码为 UTF16,这符合预期和设计。您需要:

  • 调整您的 C++ 代码以在 UTF16 上运行,或者
  • 使用另一种编码的自定义编码,例如UTF8 或 UTF32。

关于c# - 如何通过 p/invoke 将 C# 字符串传递给 linux/glibc wchar_t * 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54696296/

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