我正在开发一个带有 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/