我必须将C ++ DLL转换为C#才能在项目中使用它。这是导致我麻烦的部分。这是DLL标头的C ++代码:
struct initiate_rb
{
unsigned char Rem_Add;
unsigned char Features_Supported_1_m;
struct add_addr_param Add_Addr_Param;
};
struct add_addr_param
{
unsigned char D_Type;
unsigned char D_Len;
struct
{
unsigned char Network_Address[6];
unsigned short MAC_Address_Len;
unsigned char * MAC_Address;
} S_Addr;
};
我不知道如何在C#中处理这个问题。以下是我迄今取得的成就:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
unsafe struct initiate_rb
{
public byte Rem_Add;
public byte Features_Supported_1_m;
public add_addr_param Add_Addr_Param;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
unsafe struct add_addr_param
{
public byte D_Type;
public byte D_Len;
[StructLayout(LayoutKind.Sequential)]
public struct S_Addr
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
public byte[] Network_Address;
public ushort MAC_Address_Len;
public byte* MAC_Address;
};
}
我使用Pack = 1
,因为在我的DLL头文件中有行#pragma pack (1)
问题是,当我必须使用这个结构时,这不起作用。它返回一个错误代码。 首先,关于这种结构翻译,我做得对吗?
感谢您的帮助。
答案 0 :(得分:1)
我不确定这些属性,但我相信第二个结构不应该嵌套在C#中,因为C ++中的结构在结束括号之后定义了结构类型的变量。
[StructLayout(LayoutKind.Sequential, Pack = 1)]
unsafe struct dpc2_add_addr_param
{
public byte D_Type;
public byte D_Len;
public S_Addr S_Addr;
}
[StructLayout(LayoutKind.Sequential)]
public struct S_Addr
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
public byte[] Network_Address;
public ushort MAC_Address_Len;
public byte* MAC_Address;
};
答案 1 :(得分:1)
事实上我解决了这个问题。问题是我使用了initiate_rb
struct
unsafe struct initiate_rb
{
public byte Rem_Add;
public byte Features_Supported_1_m;
public add_addr_param Add_Addr_Param;
public initiate_rb(int networkAddressLength) : this()
{
Rem_Add = (byte)0;
Features_Supported_1_m = (byte)0;
add_addr_param = new Add_Add_Param(networkAddressLength);
}
}
和add_addr_param
的构造函数:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
unsafe struct add_addr_param
{
public byte D_Type;
public byte D_Len;
[StructLayout(LayoutKind.Sequential)]
public struct S_Addr
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
public byte[] Network_Address;
public ushort MAC_Address_Len;
public byte* MAC_Address;
};
public add_addr_param(int networkAddressLength) : this()
{
D_Type = (byte)0;
D_Len = (byte)0;
S_Addr.Network_Address = new byte[6]; //problem with this line
}
}
这就是问题所在。由于我删除了这一行,代码运行正常。实际上我不需要构造函数,因为所有参数都必须设置为0。
感谢您的帮助!