C #: sorting a structure containing arrays

I am doing some work in C #. I have the following structure:

#pragma pack(push,1)
typedef struct
{
    unsigned __int64 Handle;
    LinkType_t Type;
    LinkState_t State;
    unsigned __int64 Settings;
    signed __int8 Name[MAX_LINK_NAME];
    unsigned __int8 DeviceInfo[MAX_LINK_DEVINFO];
    unsigned __int8 Reserved[40];
} LinkInfo_t;

This is my attempt to convert it to a C # structure:

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LinkInfo_t
{
    [MarshalAs(UnmanagedType.U8)]
    public UInt64 Handle;
    MarshalAs(UnmanagedType.I4)]
    public LinkType_t Type;
    [MarshalAs(UnmanagedType.I4)]
    public LinkState_t State;
    [MarshalAs(UnmanagedType.U8)]
    public UInt64 Settings;
    [MarshalAs(UnmanagedType.LPStr, SizeConst = MAX_LINK_NAME)]
    public string Name;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = MAX_LINK_DEVINFO, ArraySubType = UnmanagedType.U1)]
    public byte[] DeviceInfo;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 40, ArraySubType = UnmanagedType.U1)]
    public byte[] Reserved;
}

However, whenever I initialize the structure, the Name, DeviceInfo, and Reserved fields are null. How to fix it?

+5
source share
3 answers

For arrays, try using the modifier fixed:

    public fixed byte DeviceInfo[MAX_LINK_DEVINFO];
    public fixed byte Reserved[40];
+7
source

whenever I initialize the structure, Name, DeviceInfo and reserved fields are all set to null

, (BTW, [MarshalAs] , - , ). null, , .

+3

, , . . "" , "". , . - .

, , C .

typedef struct {
    int messageType;
    BYTE payload[60];
} my_message;

/**
* \param[out] msg    Where the message will be written to
*/
void receiveMessage(my_message *msg);

/*
* \param[in] msg    The message that will be sent
*/
void sendMessage(my_message *msg);

# C.

[StructLayout(LayoutKind.Sequential, Size = 64), Serializable]
struct my_message
{
    int messageType;
    [MarshalAs(UnmanagedType.ByValArray,SizeConst = 60)]
    byte[] payload;

    public initializeArray()
    {
        //explicitly initialize the array
        payload = new byte[60];
    }
}

Since msg in receiveMessage () is documented as [out], you do not need to do anything special for the array in the structure before passing it to the function. i.e:.

my_message msg = new my_message();
receiveMessage(ref msg);
byte payload10 = msg.payload[10];

Since msg in sendMessage () is documented as [in], you will need to populate the array before calling the function. Before filling the array, the array must be explicitly created before using it. i.e:.

my_message msg = new my_message();
msg.initializeArray();
msg.payload[10] = 255;
sendMessage(ref msg);

The call to initializeArray () should create an instance of the array in the previously allocated space created in the structure for this array.

0
source

All Articles