gpt4 book ai didi

c# - 从 C# 传递的字符串与 C++ 字符串不同,都是 const char

转载 作者:行者123 更新时间:2023-11-27 23:46:33 25 4
gpt4 key购买 nike

我有一个 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,但没有任何改变。

我在哪里犯了错误?谢谢

最佳答案

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

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 .

关于c# - 从 C# 传递的字符串与 C++ 字符串不同,都是 const char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50104165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com