日期:2014-05-18  浏览次数:20770 次

C语言的这个操作用C#该怎么操作?
C/C++ code

typedef struct
{
    unsigned char ucOp;
    unsigned char ucHType;
    unsigned char ucHLen;
    unsigned char ucHops;
    unsigned long ulXID;
    unsigned short usSecs;
    unsigned short usFlags;
    unsigned long ulCIAddr;
    unsigned long ulYIAddr;
    unsigned long ulSIAddr;
    unsigned long ulGIAddr;
    unsigned char pucCHAddr[16];
    char pcSName[64];
    char pcFile[128];
    unsigned char pucVend[64];
}
tBOOTPPacket;


tBOOTPPacket *pPacket;
unsigned char pcPacketData[700];
pPacket = (tBOOTPPacket *)pcPacketData;


上面这个转换该怎么实现?只要把byte数组对应的搞在这个结构体里面就可以了,折腾半天不会

------解决方案--------------------
C# code
[StructLayoutAttribute(LayoutKind.Sequential)]
public struct tBOOTPPacket
{
    byte ucOp;
    byte ucHType;
    byte ucHLen;
    byte ucHops;
    uint ulXID;
    ushort usSecs;
    ushort usFlags;
    uint ulCIAddr;
    uint ulYIAddr;
    uint ulSIAddr;
    uint ulGIAddr;
    [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 16)]
    byte[] pucCHAdd;
    [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 64)]
    byte[] pcSName;
    [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 128)]
    byte[] pcFile;
    [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 64)]
    byte[] pucVend;
}

//字节数组转结构

byte[] bytes = new byte[300];

Type type = typeof(tBOOTPPacket);
int size = Marshal.SizeOf(type);
IntPtr p = Marshal.AllocHGlobal(size);
Marshal.Copy(bytes, 0, p, size);
tBOOTPPacket obj = (tBOOTPPacket)Marshal.PtrToStructure(p, type);
Marshal.FreeHGlobal(p);