gpt4 book ai didi

c# - 在 WinCE 中将结构数组从 C++ 编码到 C#

转载 作者:太空宇宙 更新时间:2023-11-04 13:07:01 24 4
gpt4 key购买 nike

我正在尝试在 Windows CE 程序和 compact framework 2.0 上将以下结构从 c++ 编码到 c#。我在编码字符串时遇到了很多困难。

我有这个 C++ 代码:

#define Console_Parameters_MAX 50

struct AllParameters {
Parameter Parameters[Console_Parameters_MAX];
} ;

struct Parameter {
int Index;
int Id;
char Value[20];
};

extern "C" {
BOOL GetAllConsoleParameters(AllParameters *pItem);
}

这是对应的c#代码:

[StructLayout(LayoutKind.Sequential)]
public struct AllParameters {
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 50)]
public Parameter[] Parameters
}

[StructLayout(LayoutKind.Sequential)]
public struct Parameter {
public int Index;
public int Id;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
public byte[] Value;
}

[DllImport("exemple.dll", SetLastError = true)]
public static extern bool GetAllConsoleParameters([MarshalAs(UnmanagedType.Struct)] ref AllParameters pItem);

这就是我调用它的方式:

AllParameters item = new AllParameters();
if (AppAPI.GetAllConsoleParameters(ref item)) {
var array = item.Parameters;
}

当我调用 GetAllConsoleParameters 时,我得到异常 NotSupportedException。我尝试了很多配置但没有成功。

任何人都可以建议如何实现它吗?

提前致谢

最佳答案

这对我来说适用于 Windows 桌面。您可能必须在 C DLL 和 C# DllImport 属性中将调用约定更改为 Cdecl,因为我在这里读到 Cdecl 在 Windows CE 上是标准的:https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.callingconvention(v=vs.110).aspx

C 代码:

extern "C" {
__declspec(dllexport) BOOL __stdcall GetAllConsoleParameters(AllParameters *pItem)
{
pItem->Parameters[0].Index = 0;
pItem->Parameters[0].Id = 42;
CopyMemory(&pItem->Parameters[0].Value[0], "Hello World", 12);
pItem->Parameters[1].Index = 1;
pItem->Parameters[1].Id = 43;
CopyMemory(&pItem->Parameters[1].Value[0], "Hello World 43", 15);
return TRUE;
}
}

C#代码:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
struct Parameter
{
int Index;
int Id;
//char Value[20];
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
string Value;
};

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
struct AllParameters
{
//Parameter Parameters[Console_Parameters_MAX];
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 50)]
Parameter[] Parameters;
};

class Program
{
[DllImport("MarshalC.dll", CallingConvention = CallingConvention.StdCall)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetAllConsoleParameters(ref AllParameters pItem);

static void Main(string[] args)
{
var size = Marshal.SizeOf<AllParameters>();
AllParameters all = new AllParameters();
bool result = GetAllConsoleParameters(ref all);
}
}

关于c# - 在 WinCE 中将结构数组从 C++ 编码到 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41747895/

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