c# - 将字符串转换为 char* 到字符串(C# -> C -> C++)

标签 c# c++ c string type-conversion

我正在开发一个带有 C 包装器的 C++ DLL,以便能够在不同的语言上使用它。现在,我也在用 C# 开发一个调用我的 DLL 的插件。

我想要的是将一个字符串(文件路径)作为我的 DLL 的参数传递,以便能够在我的 DLL 上使用它。

C#

[DllImport(DllName, CallingConvention = DllCallingConvention)]
public static extern IntPtr AllocateHandle(string filename);

C 包装器

LPVOID SAMPLEDLL_API CALLCONV_API AllocateHandle(char* filename);

C++ 类构造函数

CustomData::CustomData(char* filename)
{
    _filename = filename; // string _filename;
}

当我将 _filename 保存在文件上时(因为我没有找到使用 DLL 上的断点进行调试的方法),我有类似 ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ0à×。我尝试了不同的解决方案将 char* 转换为字符串,但结果仍然相同。

预先感谢您的帮助。

最佳答案

问题是 C# 中的字符串是 Unicode。 cpp中的字符串是ansi字符串。你必须告诉 C# 字符串必须是 ansi:

[DllImport(DllName.dll, CallingConvention=CallingConvention.StdCall, CharSet=CharSet.Ansi)]
static extern IntPtr AllocateHandle(string filename);

您还可以将字符串长度作为第二个参数传递,这样您就可以知道 cpp 端的字符串长度是多少。

[编辑]

根据一些评论,您还可以尝试将 [char *] 更改为 [wchar_t *],这是 unicode。那么你当然应该在 C# 端使用适当的属性:CharSet=CharSet.Unicode

关于c# - 将字符串转换为 char* 到字符串(C# -> C -> C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49447789/

相关文章:

c++ - GetComputerNameW 导致 Windows 10 中的缓冲区溢出

c++ - boost::spirit -- 试图编译最简单代码的编译器错误

c - 连接到 Redis 时,Unix 套接字比 tcp 慢

c - 为什么我得到正确的输出,即使代码在逻辑上是不正确的

c# - 如何在通用应用程序中禁用任务并行库的 ETW 事件源?

c# - ASP :menu in safari and chrome

c++ - 你如何告诉 pyximport 使用 cython --cplus 选项?

具有多种数据类型的 C# 自定义 app.config

c# - CHAR(1) 字段中出现 ORA-12899 错误,但我只发送 'C'

c - 非标准的特殊文档 block 和 doxygen