从C#传递的字符串与C++字符串不同,都是常量字符

passed strings from C# is different with C++ strings , both are const char

本文关键字:字符串 字符 常量 C++      更新时间:2023-10-16

我有一个c#程序,可以从c ++ dll检查数据库字符串。

我已经阅读了此页面:

  • 如何使用DLLImport将字符串从C#传递到C++(以及从C++传递到C#(?
  • 将字符串从 C# 传递到 C++ DLL 并返回 -- 最小示例

我的字符串传递得很好,没有错误,但我的问题是它们在 dll 中不匹配C++。

我试图用消息框、控制台和所有内容检查它们,它们在字符、大小、文本......

但是如果 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++,说...输入是"你好世界!

但它总是返回 0

另外,我尝试将它们转换为 wchar_t , std::string 与 find(( 但没有任何变化。

我在哪里犯错误?谢谢

你不能像这样比较字符串:

if (string_from_csharp == "hello world!" )

如果你绝对需要使用char*,请使用strcmp或strncmp。

extern "C" __declspec(dllexport) int check_string(const char* string_from_csharp);
bool check_string(const char* string_from_csharp)
{
  return (strcmp(string_from_csharp, "hello world!") == 0);
}

您可能希望使用std::string,因为您处于C++。在这种情况下,您将使用 std::string::compare。

正确答案属于马丁·韦龙诺和汉斯·帕桑特(@hans-passant @martin-véronneau(

CharSet.Unicode 是错误的,你需要 CharSet.Ansi 来匹配一个 char* 论点。并且您需要在 C 语言中正确比较字符串 你使用 strcmp((。至少字符集不匹配应该很容易 若要使用调试器进行发现,请确保知道如何调试本机代码 从 C# 调用时。– 汉斯·帕桑特

谢谢汉斯和马丁! 问题CharSet = CharSet.Unicode,我改CharSet = CharSet.Ansi,现在一切正常!

正如 tkausl 和 Daisy 在评论中提到的,我相信C++您正在比较指针值而不是实际的字符串值。在您的情况下,我认为进行比较的最简单方法是使用 strcmp 比较 2 个字符串。