Creating struct instead of class using ModuleBuilder.DefineType

  • Thread starter Thread starter Marek
  • Start date Start date
M

Marek

Hi
I am trying to dynamically create a struct using the following code:

TypeBuilder typeBuilder = moduleBuilder.DefineType("MyStruct",
TypeAttributes.Public);

It appears that this method will only ever create classes for me. Is there
any way of dynamically creating a struct? I noticed that other constructs
such as enums have their own equivalent define method (DefineEnum), but
couldn't see a way of doing this for structs.

I have to use a struct as this object is passed to a FORTRAN DLL which does
not like the class equivalent.

Best regards

Marek
 
Have you tried using typeof(ValueType) as the parent? At the IL level,
both struct and class are IL classes - i.e. here is the sig from Int32
(IL view in reflector):

..class public sequential ansi serializable sealed beforefieldinit
Int32
extends System.ValueType
implements System.IComparable, System.IFormattable,
System.IConvertible, System.IComparable`1<int32>,
System.IEquatable`1<int32>

That seems to work - at least in a quick test CreateType().IsValueType
returned true.

Of course, you still might have some fun getting this new Type into
your external API...

Marc
 
(example)

AssemblyName an = new AssemblyName("Foo");
AssemblyBuilder ab =
AppDomain.CurrentDomain.DefineDynamicAssembly(an,
AssemblyBuilderAccess.Run);
ModuleBuilder mb = ab.DefineDynamicModule("Foo");
TypeBuilder tb = mb.DefineType("Foo", TypeAttributes.Public |
TypeAttributes.Sealed | TypeAttributes.SequentialLayout |
TypeAttributes.Serializable, typeof(ValueType));
Type type = tb.CreateType();
bool isVal = type.IsValueType;
 
Hi Marc
You're a star. That worked a treat thanks.

Nice use of the parent type parameter - I looked at it but didn't think of
using it in this way.

Best regards

Marek
 
Back
Top