我正在尝试使用 ilgenerator.emit 做一个 msgbox,但是当我运行代码时出现异常:
从呼叫目的地生成的异常
这是我的代码:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim assemblyName As AssemblyName = New AssemblyName("SamAsm")
Dim assemblyBuilder As AssemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave)
'Creating module
Dim moduleBuilder As ModuleBuilder = assemblyBuilder.DefineDynamicModule("SamAsm.exe")
Creating class file
Dim typeBuilder As TypeBuilder = moduleBuilder.DefineType("SamAsmType", TypeAttributes.Public Or TypeAttributes.Class)
Creating Main Method
Dim methodBuilder1 As MethodBuilder = typeBuilder.DefineMethod("Main", MethodAttributes.Static Or MethodAttributes.Public, GetType(Void), New System.Type() {GetType(String)})
'Generating Code for method builder in IL
Dim ilGenerator As ILGenerator = methodBuilder1.GetILGenerator
ilGenerator.Emit(OpCodes.Ldstr, "test")
ilGenerator.EmitCall(OpCodes.Call, GetType(System.Windows.Forms.MessageBox).GetMethod("Show", {GetType(String)}), {GetType(String)})
ilGenerator.Emit(OpCodes.Ret)
'Creating Class object (type) and accessing main method
Dim SamAsmType As Type = typeBuilder.CreateType
SamAsmType.GetMethod("Main").Invoke(Nothing, New String() {Nothing})
'Creating Entry Point and saving assembly
assemblyBuilder.SetEntryPoint(methodBuilder1, PEFileKinds.WindowApplication)
assemblyBuilder.Save("SamAsm.exe")
End Sub