gpt4 book ai didi

c# - 如何在 .NET Compact Framework(C#) 中编码 "Cstring"类型?

转载 作者:太空宇宙 更新时间:2023-11-03 11:48:19 24 4
gpt4 key购买 nike

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

DLL名称: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”? 任何有关它的信息将不胜感激!

最佳答案

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

您可以将 string 编码为 char[],因为 char[] 是原生类型。您需要将要 P/Invoke 的函数的参数作为基本类型,如 intboolchar struct,但不是类。在这里阅读更多内容:

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*,因此请注意非托管版本采用的字符串类型。此版本使用TCHAR,当使用/UNICODE编译时变成wchar_t。这就是为什么您需要在 DllImport 属性中指定 CharSet=CharSet.Unicode

关于c# - 如何在 .NET Compact Framework(C#) 中编码 "Cstring"类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2801134/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com