Search code examples
c#c++pointerscode-translation

How can I put an array inside a struct in C#?


C++ code:

struct tPacket
{
    WORD word1;
    WORD word2;
    BYTE byte1;
    BYTE byte2;
    BYTE array123[8];
}

static char data[8192] = {0};
...
some code to fill up the array
...
tPacket * packet = (tPacket *)data;

We can't do that as easy in C#.

Please note there is an array in the C++ structure.

Alternatively, using this source file could do the job for us, but not if there is an array in the structure.


Solution

  • What you are looking for (if you are using a similar structure definition like @JaredPar posted) is something like this:

    tPacket t = new tPacket();
    byte[] buffer = new byte[Marshal.SizeOf(typeof(tPacket))];
    socket.Receive(buffer, 0, buffer.length, 0);
    
    GCHandle pin = GCHandle.Alloc(buffer, GCHandleType.Pinned);
    t = (tPacket)Marshal.PtrToStructure(pin.AddrOfPinnedObject(), typeof(tPacket));
    pin.free();
    
    //do stuff with your new tPacket t