【问题标题】:passed strings from C# is different with C++ strings , both are const char从 C# 传递的字符串与 C++ 字符串不同,两者都是 const char
【发布时间】:2018-10-10 18:20:49
【问题描述】:

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

我已经阅读了这些页面:

我的字符串顺利通过,没有错误,但我的问题是 它们在 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# 调用时调试本机代码。

标签: c# c++


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    if (string_from_csharp == "hello world!" )
    

    如果您绝对需要使用 char*,请使用 strcmpstrncmp

    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

    【讨论】:

    • 谢谢,但不幸的是你的代码不起作用,它总是返回 0 ,如果我输入 "hello world!"它返回 false ,如果我输入“其他任何内容”,它返回 false ...您是否测试过您的代码?用 c# 吗?
    • @SamuelHardson:您是否按照 Hans Passant 的要求更改了 CharSet?
    • @PaulF 是的,我做了,我标记了这个答案,并添加了 Hans Passant 的另一个答案。谢谢
    【解决方案3】:

    正确答案属于 Martin Véronneau 和 Hans Passant (@hans-passant @martin-véronneau)

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-20
      • 1970-01-01
      • 1970-01-01
      • 2018-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多