c# - Fixed Object to ByteArray -
c# - Fixed Object to ByteArray -
i have simple object looks this
public class foo { public uint32 1 { get; set; } public uint32 2 { get; set; } public uint32 3 { get; set; } public uint32 4 { get; set; } }
i tried code i've found somewhere on net
public byte[] objecttobytearray(object obj) { memorystream fs = new memorystream(); binaryformatter formatter = new binaryformatter(); formatter.serialize(fs, obj); byte[] rval = fs.toarray(); fs.close(); homecoming rval; }
but somehow returning bytearray 248 bytes size, expected 4 bytes x 4 fields = 16 bytes.
question: what's cleanest way convert bytearray? , should resulting bytearray 16 bytes size?
thanks in advanced.
binaryformatter saves lot of type info able deserialize properly. if want compact serialization or comunicate via strict protocol, have explictly this:
public byte[] tobytearray() { list<byte> result = new list<byte>(); result.addrange(bitconverter.getbytes(one)); result.addrange(bitconverter.getbytes(two)); result.addrange(bitconverter.getbytes(three)); result.addrange(bitconverter.getbytes(four)); homecoming result.toarray(); }
here convert each of uint32 byte array , store in resulting array.
edit turns out there way using struct
, marshal
first create struct
, mark attributes that:
[structlayout(layoutkind.sequential, pack = 1)] struct mystruct { [marshalas(unmanagedtype.byvaltstr, sizeconst = 50)] public string stringfield; public int intfield; }
here layoutkind.sequential
tells clr maintain fields in memory in same order declaration. without pack = 1
structures can take more memory required. struct
1 short
field , 1 byte
needs 3 bytes, default it's size 4 (processor has instructions manipulating single byte, 2 bytes , 4 bytes, clr sacrifices 1 byte per instance of struct cut down amount of instructions of machine code half). can utilize marshal
re-create bytes:
public static byte[] getbytes<t>(t str) { int size = marshal.sizeof(str); var bytes = new byte[size]; intptr ptr = marshal.allochglobal(size); seek { marshal.structuretoptr(str, ptr, true); marshal.copy(ptr, bytes, 0, size); homecoming bytes; } { marshal.freehglobal(ptr); } }
everything works fine simple types. complex types such string
you'll have utilize marshalas
attribute , it's using bit more complicated (in illustration told clr marshal string array of fixed 50 bytes size).
c#
Comments
Post a Comment