【发布时间】:2018-10-10 18:20:49
【问题描述】:
我有一个 c# 程序,可以检查来自 c++ dll 的数据库字符串。
我已经阅读了这些页面:
- How to pass strings from C# to C++ (and from C++ to C#) using DLLImport?
- Passing strings from C# to C++ DLL and back -- minimal example
我的字符串顺利通过,没有错误,但我的问题是 它们在 C++ dll 中不匹配。
我尝试使用 Messagebox 、 Console 和 Everything 来检查它们,它们在字符、大小、文本上都相同......
但 If Else 总是返回 false ...
我的 C++ 代码(test_match.dll):
extern "C" __declspec(dllexport) int check_string(const char* string_from_csharp);
int check_string(const char* string_from_csharp)
{
if (string_from_csharp == "hello world!" ){
return 1;
}else{
return 0;
}
}
我的 C# 代码:
[DllImport("test_match.dll",
CallingConvention = CallingConvention.Cdecl ,
CharSet = CharSet.Unicode)]
private static extern int check_string(string string_from_csharp)
我的 C# 使用代码 (WPF):
int get_match_state = check_string(inputtext.Text);
C++ 中的MessageBox,说...输入是“hello world!”
但它总是返回 0
另外,我尝试使用 find() 将它们转换为 wchar_t、std::string 但没有任何改变。
我在哪里犯了错误? 谢谢
【问题讨论】:
-
您无法将
const char*与==进行比较。 -
我不是 C++ 程序员,但看起来您目前正在比较 指针。如果您的参数是 C++
string我希望==以更“基于内容”的方式运行。 -
CharSet.Unicode 错误,您需要 CharSet.Ansi 来匹配 char* 参数。并且您需要正确比较字符串,在 C 语言中您使用 strcmp()。至少 CharSet 不匹配应该很容易通过调试器发现,请确保您知道如何在从 C# 调用时调试本机代码。