从C#传递的字符串与C++字符串不同,都是常量字符
passed strings from C# is different with C++ strings , both are const char
我有一个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 个字符串。
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 尝试将字符串/字符转换为整数会产生意外结果
- 为什么没有访问所有字符串字符?
- 将子字符串字符从字符串值转换为 int,然后将其分配给 int 变量
- 如何将字符串字符与结构数组进行比较?
- 将单个字符串/字符输入串行监视器
- 读取字符串字符时出错 - 对于数组中的字符串值
- C++ C 样式字符串/字符数组的大小 - 优化
- 读取字符串字符时出错
- C++ 使用 Strtok 读取字符串字符时出错
- 如何将 int 数组的 1 个元素转换为字符串/字符
- 在另一个字符串中逐个复制字符串字符
- 将字符串字符映射到矢量
- MBED RTOS将Float转换为字符串/字符阵列
- 如何使用字符串字符数组中的 ++ 运算符访问下一个字符串
- 如何比较C++中的单个字符串字符?
- 内部字符串/字符如何在 int 和 float 中存储
- 将十六进制转换为可打印的字符串/字符
- wcscpy_s后读取字符串字符时出错
- 检查字符串字符和长度