-7

I read following some where. Can somebody shed some light on it probably with an example

'the message could even be a struct that is just converted to a byte array which is outputted on the debug UART.

Then on the PC side, the incoming byte array can be easily converted back to a struct like object.'

user3061597
  • 477
  • 1
  • 4
  • 8
  • 1
    Serialize using a binary formatter? And deserialize back? – nawfal Aug 24 '15 at 11:58
  • Nah, you'd have to use the BitConverter-Methods. But I'd suggest writing a C-Library for that which can convert byte streams to structs more easily. There it's just pointer logic actually. – PhilMasteG Aug 24 '15 at 12:03
  • Try this: http://stackoverflow.com/questions/2871/reading-a-c-c-data-structure-in-c-sharp-from-a-byte-array – CKII Aug 24 '15 at 12:05

1 Answers1

2

You can use unsafe to access any blittable (arrays, strings, structs etc.) types as a byte pointer.

Local variables of value types don't have to be pinned:

public unsafe void ReadAsBytePointer(MyStruct obj)
{
    byte* ptr = (byte*)&obj;
    ...    
}

Arrays must be pinned. The easiest solution is to use fixed:

public unsafe void ReadAsBytePointer(MyStruct[] input)
{
    fixed(MyStruct* ptr = input)
    {
        byte* byteArray = (byte*)ptr;
    }
}

For a general case without adding unsafe to your code you can use GCHandle:

static byte[] GetBytes<T>(T input)
  where T : struct
{
    int size = Marshal.SizeOf(typeof(T));
    byte[] result = new byte[size];
    GCHandle gc = GCHandle.Alloc(input, GCHandleType.Pinned);
    try
    {
        Marshal.Copy(gc.AddrOfPinnedObject(), result, 0, size);
    }
    finally
    {
        gc.Free();
    }
    return result;
}
GeirGrusom
  • 999
  • 5
  • 18