更新时间:2021-11-20 08:48:07
您不能元帅的CString
,因为它不是一个原生型 - 这是一个封装了一个C ++类一个字符
阵列。
You can't marshal CString
as it's not a native type - it's a C++ class that wraps up a char
array.
您可以名帅字符串
到的char []
为的char []
是本机类型。你需要有参数到你想要的功能的P / Invoke为基本类型,如 INT
,布尔
, 字符
或结构
,而不是类。在这里阅读更多:
You can marshal string
to char[]
as char[]
is a native type. You need to have the parameters to the function you want to P/Invoke into as basic types like int
, bool
, char
or struct
, but not classes. Read more here:
http://msdn.microsoft.com/en-us/library/ aa446536.aspx
为了调用该采取的CString作为参数的函数,你可以做这样的事情:
In order to call functions that take CString as an argument you can do something like this:
//Compile with /UNICODE
extern "C" MFCINTEROP_API int GetStringLen(const TCHAR* str) {
CString s(str);
return s.GetLength();
//Or call some other function taking CString as an argument
//return CallOtherFunction(s);
}
[DllImport("YourDLL.dll", CharSet=CharSet.Unicode)]
public extern static int GetStringLen(string param);
在我们传递了一个 System.String
可调集到的char * / wchar_t的* $ C $上面的P / Invoke函数C>。非托管函数然后创建
的CString
的实例,并与这一点。
In the above P/Invoke function we pass in a System.String
which can marshal to char*/wchar_t*
. The unmanaged function then creates a instance of CString
and works with that.
在默认情况下 System.String
被编组为的char *
,所以要小心什么样的字符串的非托管的版本需要。此版本使用 TCHAR
,变成 wchar_t的
在与 / UNI code编译
。这就是为什么你需要指定字符集= CharSet.Uni code
在的DllImport
属性。
By default System.String
is marshalled to char*
, so be careful with what kind of string the unmanaged version takes. This version uses TCHAR
, which becomes wchar_t
when compiled with /UNICODE
. That's why you need to specify CharSet=CharSet.Unicode
in the DllImport
attribute.