c++ - Mapping byte array data to structs in C# -
i've been wrestling problem many hours turn here see if has idea how solve problem. have legacy c++ program sends packets via sockets. these contain c++ structs, thought easy define struct looking 1 in c++ in c# application , read byte array. i've noticed it's not simple , think i've boiled down problem alignment, still can't head round it.
my c++ struct looks this:
typedef struct { int int_1; short short_1; long long_1; char char_11[11]; long long_2; short short_2; int int_2; } test_klient_rec, *ptest_klient_rec;
which thought translate c# struct this:
[structlayout(layoutkind.explicit, pack=0)] public struct test_klient_rec { [fieldoffset(0)] [marshalas(unmanagedtype.i4)] public int int_1; // 4 [fieldoffset(4)] [marshalas(unmanagedtype.i2)] public short short_1; // 2 [fieldoffset(6)] [marshalas(unmanagedtype.i4)] public int long_1; // 4 [fieldoffset(12)] [marshalas(unmanagedtype.byvaltstr, sizeconst=11)] public string char_11; // 11 [fieldoffset(22)] [marshalas(unmanagedtype.i4)] public int long_2; // 4 [fieldoffset(26)] [marshalas(unmanagedtype.i2)] public short short_2; // 2 [fieldoffset(28)] [marshalas(unmanagedtype.i4)] public int int_2; // 4 }
the problem seems how c# maps short (putting in padding of 2 bytes?) causes rest of struct badly aligned , creating garbage data. possible make work in way? i'm not fuzzed using structs in c# if classes makes easier.
the result of when using test data seems int_1, long_1 , short_1 correct values , else garbage, that's why suspect short problem here.
any thoughts more welcomed.
/j
edit: why have 12 instead of 10 string offset because seems char ararys have start @ dword, if put 10 instead think should (i know math thank you) crash "could not load type 'test_klient_rec' assembly 'socketandstructtest, version=1.0.0.0, culture=neutral, publickeytoken=null' because contains object field @ offset 10 incorrectly aligned or overlapped non-object field."
your fieldoffsets
don't line way you'd expect. example, after 2 i_4's , i_2, have fieldoffset(12)
, whereas think you'd want fieldoffset(10)
.
also, think need apply [structlayout(layoutkind.explicit)]
struct
.
Comments
Post a Comment