Convert array<Byte> to Struct in managed CPP

99 Views Asked by At

This has to be one of the most common things to do when working with IP Sockets. You get the data as a array and then you probably need to convert it to a struct.

The code looks something like this:

    array<Byte> ^ buffer = gcnew array<Byte>(2048);

while( nDataLen < 16 )
{
    nDataLen += m_Socket->Receive( buffer, 16-nDataLen, SocketFlags::None );
    m_Socket->Poll( 100000, SelectMode::SelectRead );
}

Now I need to take the 16 Bytes I just received and convert them to the following struct;

[StructLayout(LayoutKind::Explicit, Size=16, Pack=1,CharSet=CharSet::Ansi)]
public ref struct ResponseHeader
{
   public:

[FieldOffset(0)]    
UInt32  m_StartMessage;     // STRP

[FieldOffset(4)]    
Int32   m_MessageLength;    //  Total message length

[FieldOffset(8),MarshalAs(UnmanagedType::ByValTStr,SizeConst=6)]    
String ^    m_Status;       //  Message Status

[FieldOffset(14),MarshalAs(UnmanagedType::ByValTStr,SizeConst=2)]   
String ^    m_Reason;       //  Message Reason

};

I would like to see a cast from the array directly to the struct but I am not sure that is doable in managed code, simple in native cpp.

If there isn't a way to cast this, then what is the best way to proceed?

0

There are 0 best solutions below