2

如何在 .NET Compact Framework(C#) 中编组“Cstring”的类型?

DLLname:Test_Cstring.dll(操作系统为WinCE 5.0),源代码:

extern "C" __declspec(dllexport) int GetStringLen(CString str)
{ 
   return str.GetLength();
}

我在 .NET Compact Framework(C#) 中编组它,例如:

[DllImport("Test_Cstring.dll", EntryPoint = "GetStringLen", SetLastError = true)]
public extern static int GetStringLen(string s);

private void Test_Cstring()
{
   int len=-1;
   len=GetStringLen("abcd");
   MessageBox.Show("Length:"+len.ToString()); //result is -1,so PInvoke is unsuccessful!
}

.NET CF 中的“GetStringLen”方法不成功!如何编组这种类型的“Cstring”?任何有关它的信息将不胜感激!

4

2 回答 2

2

您不能编组CString,因为它不是本机类型 - 它是一个包含char数组的 C++ 类。

您可以编组stringchar[]char[]生类型。您需要将要 P/Invoke 的函数的参数作为基本类型,如、int或,但不是类。在这里阅读更多:boolcharstruct

http://msdn.microsoft.com/en-us/library/aa446536.aspx

为了调用以 CString 作为参数的函数,您可以执行以下操作:

//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);        

在上面的 P/Invoke 函数中,我们传入了一个System.String可以编组到char*/wchar_t*. 然后,非托管函数创建一个实例CString并使用它。

默认情况下System.String编组为char*,因此请注意非托管版本采用哪种字符串。此版本使用TCHARwchar_t编译时使用/UNICODE. 这就是您需要在属性中指定的CharSet=CharSet.Unicode原因DllImport

于 2010-05-10T08:19:53.973 回答
0

您应该执行以下操作:

extern "C" __declspec(dllexport) int GetStringLen(LPCTSTR  str)
{ 
   CString s(str);
   return s.GetLength();
}

CString 实际上是 MFC 类型而不是本机类型。只需抓住字符串并将其转换为本地方法中的 CString 即可。

于 2010-05-10T08:20:20.613 回答