将c ++结构转换为c#结构。错误输出

时间:2018-06-26 04:54:07

标签: c++ dll struct export

我的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

GetNetworkInfo返回正常结果,但是RegNewUser输出此错误:

  

错误:无法编组类型,因为嵌入式数组实例的长度与布局中声明的长度不匹配。

我该如何解决?

0 个答案:

没有答案