Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IL, emit default constructor call

I'm generating new type at runtime, After I've generated default constructor I want to generate another one, with parameters.I'm doing it this way :

cb = tb.DefineConstructor(MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName,
                    CallingConventions.Standard, new Type[] { typeof(bool) });
GenConstructorWithParameters(cb, fields, genFields);

The problem is, that I am unable to call default constructor from method GenConstructorWithParameters, because CLR does not allow me to write something like this :

gen.Emit(OpCodes.Ldarg_0);        
gen.Emit(OpCodes.Call, cb.DeclaringType.GetConstructor(Type.EmptyTypes));//Not allowed to call .GetConstructor() on not created type!

How do I emit call to default constructor? Is it possible at all?

tb - instance of TypeBuilder, cb - ConstructorBuilder

like image 710
illegal-immigrant Avatar asked Feb 24 '23 11:02

illegal-immigrant


1 Answers

Rather than using DeclaringType.GetConstructor, you should pass your current ConstructorBuilder for the default constructor.

Basically, whilst building up a type, in places where you might use reflection based methods on existing types, you should instead pass in the builders that you're already working with.


So it would be:

gen.Emit(OpCodes.Call, defaultCB);

where defaultCB was the ConstructorBuilder you declared when defining the default constructor.

like image 172
Damien_The_Unbeliever Avatar answered Feb 26 '23 00:02

Damien_The_Unbeliever