in .net core there generic method marshal.sizeof<t>()
available (marshal.sizeof(type t)
deprecated). enumerate properties of class , marshal size of them. how do?
this code: (not mine code i'm trying port .net core)
from https://github.com/kapetan/dns/blob/master/dns/protocol/marshalling/struct.cs modifications
private static byte[] convertendian<t>(byte[] data) { var fields = typeof(t).getruntimefields().where(f => f.isstatic == false); endianattribute endian = typeof(t).gettypeinfo().getcustomattribute<endianattribute>(); foreach (fieldinfo field in fields) { if (endian == null && field.getcustomattribute<endianattribute>(false) == null) { continue; } int offset = marshal.offsetof<t>(field.name).toint32(); // *** deprecated *** // int length = marshal.sizeof(field.fieldtype); // *** doesn't work @ *** int length = field.fieldtype.gettypeinfo().structlayoutattribute.size; endian = endian ?? field.getcustomattribute<endianattribute>(false); if (endian.endianness == endianness.big && bitconverter.islittleendian || endian.endianness == endianness.little && !bitconverter.islittleendian) { array.reverse(data, offset, length); } } return data; }
what need decide generic type should used in runtime. there way it: dynamic type.
c# reference says,
the dynamic type enables operations in occurs bypass compile-time type checking. instead, these operations resolved @ run time.
so can define method:
static int getlength<t>(t obj) { return marshal.sizeof<t>(); }
and create instance of type t
dynamic reflection:
dynamic obj = activator.createinstance(field.fieldtype.gettypeinfo()); int length = getlength(obj);
the runtime choose suitable type parameter t method.
this solution has limitation can't create instance of type hasn't default constructor. may define wrapper class wrapper<t>
no real field, , create runtime in order ensure constructor works. have no idea whether works.
Comments
Post a Comment