我的C ++ dll
具有两个结构。
C ++:
typedef struct interface_info {
DWORD index;
DWORD ipv4Addr;
BYTE macAddr[6];
DWORD gateway;
}I_INFO;
typedef struct user_info {
DWORD uniqueid;
BYTE userid[32];
BYTE pwd[32];
BYTE info[5][64];
}U_INFO;
C#:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct I_INFO
{
public uint Index;
public uint ipv4Addr;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
public byte[] macAddr;
public uint gateway;
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct U_INFO
{
public uint uniqueid;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
public byte[] userid;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
public byte[] pwd;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 320)]
public byte[] info;
};
我正在调用此方法:
C ++:
void GetNetworkInfo(I_INFO *n); // Show interface Info
dword RegNewUser(U_INFO *u); // Save to test.ini
C#:
[DllImport("TestNet.dll")]
public static extern void GetNetworkInfo(ref I_INFO n);
[DllImport("TestNet.dll")]
public static extern uint RegNewUser(ref U_INFO u);
我这样称呼: C#:
I_INFO ii = new I_INFO();
GetNetworkInfo(ref ii);
MessageBox.Show(ii.index+ "\n"
+ Long2ip(ii.ipAddr) + "\n"
+ Long2ip(ii.gateway) + "\n"
+ Bytes2Str(ii.macAddr);
....
I_INFOuser = new I_INFO
{
uid = Encoding.ASCII.GetBytes("testUser"),
pwd = Encoding.ASCII.GetBytes("testPassword"),
info = Encoding.ASCII.GetBytes("hello world!")
};
try
{
RegNewUser(ref user);
}
catch(Exception err)
{
MessageBox.Show(err.ToString());
}
输出为:
GetNetworkInfo
返回正常结果,但是RegNewUser
输出此错误:
错误:无法编组类型,因为嵌入式数组实例的长度与布局中声明的长度不匹配。
我该如何解决?