c# - passed strings from C# is different with C++ strings , both are const char
问题描述
I have a c# program that checks data base strings from a c++ dll.
I already read this pages :
- 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
My strings pass well with no error but my problem is they're not matching in C++ dll.
I tried to check them out with Messagebox , Console and Everything and they are same at characters , size , text ...
but If Else always returns false ...
My C++ code ( 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;
}
}
My C# code :
[DllImport("test_match.dll",
CallingConvention = CallingConvention.Cdecl ,
CharSet = CharSet.Unicode)]
private static extern int check_string(string string_from_csharp)
My C# code of usage ( WPF ) :
int get_match_state = check_string(inputtext.Text);
MessageBox in C++ , says ... input is "hello world!"
But it always returns 0
Also , I tried to convert them to wchar_t , std::string with find() but nothing changed.
Where do I make a mistake? Thanks
解决方案
You can't compare strings like that :
if (string_from_csharp == "hello world!" )
If you absolutely need to use char*, use strcmp, or 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);
}
You may want to use std::string
since you're in C++. In that case, you'd use std::string::compare.
推荐阅读
- javascript - Node.js 中的虚拟文件系统
- neural-network - YOLOv3 卷积层数
- django - 您可以以一种相同的形式创建父对象和子对象列表吗
- makefile - .PHONY 规则出现“无事可做”错误
- python - 如何将字符串更改为浮点列表和 n 维列表的“n”?
- docker - 启动用户态代理时出错:监听 tcp 0.0.0.0:7050:绑定:地址已在使用中
- eclipse - MAC OS 上的 Team Explorer 无处不在的问题
- python-3.x - jupyter_contrib_nbextensions 选项卡未显示大型笔记本
- javascript - 尝试在测验应用程序的新组件中映射问题时收到“TypeError:无法读取未定义的属性'map'”
- typescript - 如何为打字稿类定义返回类型