DLLImport与char *参数。只有一个字符被传递 [英] DLLImport with char * arguments. Only one character being passed

查看:172
本文介绍了DLLImport与char *参数。只有一个字符被传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写了一个带有以下函数导出的C ++ DLL。

I have written a C++ DLL with the following function exported

extern "C" BOOL WINAPI SetUserPassword(const char* u, const char* p)



当从C#调用这个函数时,我使用下面的代码

When calling this from C# I am using the following code

[DllImport("mydll.dll")]
private static extern int SetUserPassword(String user, String password);

现在当 SetUserPassword 每个参数的第一个字母。我做了一些googling,发现 String 也许不是最好使用所以尝试使用IntPtr和 Marshal.StringToBSTR()但是这也没有工作。

Now when SetUserPassword is called I only get the first letter of each parameter. I did some googling and found that String was perhaps not the best to use so tried using IntPtr and Marshal.StringToBSTR() but this didn't work either.

这应该如何正确地结构?

How should this be structured correctly? I am able to modify the C++ DLL if required.

推荐答案

唯一有意义的是,你的C#代码实际上是:

The only thing that makes sense is that your C# code is actually:

[DllImport("mydll.dll", CharSet = Unicode)]
private static extern int SetUserPassword(String user, String password);

当你这样做,你传递一个宽字符的字符串到你的C ++代码,

When you do this you pass a wide character based string to your C++ code and since it expects single byte characters it interprets the 0 byte in the second half of the first two byte character as a string terminator.

你应该这样写:

[DllImport("mydll.dll", CharSet = Ansi)]
private static extern int SetUserPassword(String user, String password);

或者事实上你可以像你的问题一样写,因为 Ansi 是默认值。

Or in fact you could write it exactly as in your question because Ansi is the default.

事实上,支持 Ansi 字符集,所以唯一合理的解决方案是让你的C ++代码接受宽字符串。

And in fact it turns out that you are on CE which does not support Ansi character set and so the only reasonable solution is to make your C++ code accept wide character strings.

这篇关于DLLImport与char *参数。只有一个字符被传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆