TypeBuilder set type size

87 views Asked by At

I am trying to build a dynamic type and set its size, like [StructLayout(LayoutKind.Sequential, Size=100)] can. I have the following code:

Type structLayoutAttr = typeof(StructLayoutAttribute);
ConstructorInfo structLayoutAttrCtor = structLayoutAttr.GetConstructor(new[]{typeof(LayoutKind)});
object[] structLayoutAttrCtorArgs = new object[]{LayoutKind.Explicit};
FieldInfo[] structLayoutAttrSizeField = new FieldInfo[]{structLayoutAttr.GetField("Size")};
CustomAttributeBuilder cb = new CustomAttributeBuilder(structLayoutAttrCtor, structLayoutAttrCtorArgs, structLayoutAttrSizeField, new object[]{size});
tb.SetCustomAttribute(cb);
type = tb.CreateType();

However, this code fails at the last step - CreateType throws TypeLoadException about bad format. Is there a proper way to apply the attribute?

1

There are 1 answers

0
IS4 On BEST ANSWER

The StructLayout attribute is a special attribute, it is handled by the compiler and compiled into a special metadata, thus you can't apply it with custom attribute building. Check the DefineType overload, there is one that takes the size of the type.