首页 > 解决方案 > 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 :

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

标签: c#c++

解决方案


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.


推荐阅读