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

我有一个ac#程序,用于从c ++ dll检查数据库字符串。

我的字符串顺利通过,没有错误,但是我的问题是它们在C ++ dll中不匹配。


我试图用Messagebox,Console和Everything检查它们,它们在字符,大小,文本上是相同的...


但是如果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表示...输入是“世界您好!”


但它总是返回0


另外,我尝试使用find()将它们转换为wchar_t,std :: string,但没有任何改变。


我在哪里犯错? 谢谢


HUH函数
浏览 333回答 3
3回答

噜噜哒

正确答案属于MartinVéronneau和Hans Passant(@ hans-passant @martin-véronneau)CharSet.Unicode错误,您需要CharSet.Ansi来匹配char *参数。并且您需要正确比较字符串,使用C语言的strcmp()。至少CharSet的不匹配应该已经很容易通过调试器发现,请确保您知道从C#调用时如何调试本地代码。–汉斯·帕桑(Hans Passant)谢谢汉斯和马丁!问题是CharSet = CharSet.Unicode,我更改为CharSet = CharSet.Ansi,现在一切正常!

慕桂英3389331

我相信在C ++中,您是在比较指针值而不是实际的字符串值。在您的情况下,我认为最简单的比较方法是使用strcmp比较两个字符串。
打开App,查看更多内容
随时随地看视频慕课网APP