Home All Groups Group Topic Archive Search About

Structure to byte array and back

Author
9 Mar 2006 7:17 PM
Ken Allen
Is there a relatively painless method for converting the contents of a
structure into a byte array and back again?

I have been using Marshal to do this, but it is a pain! To get the byte
array I have to Marshal.StructureToPtr() and then use Marshal.ReadByte()
to extract each of the bytes into an array individually. The reverse is
just as painful.

Is there no general purpose (safe) mechanism for achieving the same thing?

-ken

Author
9 Mar 2006 7:37 PM
Mattias Sjögren
Ken,

>and then use Marshal.ReadByte()
>to extract each of the bytes into an array individually.

You can use Marshal.Copy to get them all at once.


Mattias

--
Mattias Sjögren [C# MVP]  mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Author
15 Mar 2006 4:42 PM
Stuart Irving
try this:

MemoryStream ms = new MemoryStream();

BinaryFormatter bf = new BinaryFormatter();

bf.Serialize(ms, myStruct);

return ms.ToArray();



Show quote
"Ken Allen" <kendr***@sympatico.ca> wrote in message
news:Ogg7d46QGHA.4300@TK2MSFTNGP14.phx.gbl...
> Is there a relatively painless method for converting the contents of a
> structure into a byte array and back again?
>
> I have been using Marshal to do this, but it is a pain! To get the byte
> array I have to Marshal.StructureToPtr() and then use Marshal.ReadByte()
> to extract each of the bytes into an array individually. The reverse is
> just as painful.
>
> Is there no general purpose (safe) mechanism for achieving the same thing?
>
> -ken
Author
15 Mar 2006 9:38 PM
Peter Bromley
Ken Allen wrote:
> Is there a relatively painless method for converting the contents of a
> structure into a byte array and back again?
>
> I have been using Marshal to do this, but it is a pain! To get the byte
> array I have to Marshal.StructureToPtr() and then use Marshal.ReadByte()
> to extract each of the bytes into an array individually. The reverse is
> just as painful.
>
> Is there no general purpose (safe) mechanism for achieving the same thing?
>
> -ken

Well, as long as you are unconcerned with endian, versioning, or struct
layout issues, this C++ code below might help:

__value struct MyStruct
    {
    ...
    };

....
MyStruct myStruct;
....
// copy to Byte array
System::Byte dstBuffer __gc[] = new System::Byte[sizeof(MyStruct)];
System::Byte __pin* dstP = &dstBuffer[0];
*((MyStruct*)(void*)dstP) = myStruct;
....
// copy from byte array (srcBuffer)
System::Byte __pin* srcP = &srcBuffer[0];
MyStruct myStruct = *((MyStruct*)(void*)srcP);


I know it looks ugly but it does work assuming the constraints I
mentioned above.

Cheers, Peter

AddThis Social Bookmark Button