We want to dynamically create a class constructor, as shown below:
public JsRF1013Wrapper(ScriptEngine scriptEngine, string jsFileFullPath) { this.ScriptEngine = scriptEngine; var jsFileContent = File.ReadAllText(jsFileFullPath); this.ScriptEngine.Execute(jsFileContent); }
we got IL:
.method public hidebysig specialname rtspecialname instance void .ctor(class [ClearScript]Microsoft.ClearScript.ScriptEngine scriptEngine, string jsFileFullPath) cil managed {
we wrote the emit code: ConstructorInfo objCtor = calculatorType.GetConstructor (new type [] {typeof (ScriptEngine), typeof (string)});
Type[] ctorParams = new Type[] { typeof(ScriptEngine), typeof(string) }; ConstructorBuilder wrapperCtor = typeBuilder.DefineConstructor( MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, CallingConventions.Standard, ctorParams); ILGenerator ctorIL = wrapperCtor.GetILGenerator(); ctorIL.Emit(OpCodes.Ldarg_0); ctorIL.Emit(OpCodes.Call, objCtor); ctorIL.Emit(OpCodes.Nop); ctorIL.Emit(OpCodes.Nop); ctorIL.Emit(OpCodes.Ldarg_0); ctorIL.Emit(OpCodes.Ldarg_1); ctorIL.Emit(OpCodes.Stfld, scriptEngineField); ctorIL.Emit(OpCodes.Ldarg_2); ctorIL.Emit(OpCodes.Call, typeof(File).GetMethod("ReadAllText", new Type[] { typeof(string) })); ctorIL.Emit(OpCodes.Stloc_0); ctorIL.Emit(OpCodes.Ldarg_0); ctorIL.Emit(OpCodes.Ldfld, scriptEngineField); ctorIL.Emit(OpCodes.Ldloc_0); ctorIL.Emit(OpCodes.Callvirt, typeof(ScriptEngine).GetMethod("Execute", new Type[] { typeof(string) })); ctorIL.Emit(OpCodes.Nop); ctorIL.Emit(OpCodes.Nop); ctorIL.Emit(OpCodes.Stfld, jsFileFullPathField); ctorIL.Emit(OpCodes.Ret);
and there is an exception called System.Reflection.TargetInvocationException when used as follows:
ICalculator calculator = (ICalculator)Activator.CreateInstance(t, new object[] { new JScriptEngine(), jsFileFullPath });
what problem?
source share