使用System.Reflection.Emit在Windows.Forms中显示MessageBox

时间:2012-12-03 13:07:56

标签: vb.net reflection reflection.emit il

我正在尝试使用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

1 个答案:

答案 0 :(得分:4)

Sub / void函数返回时,您必须确保堆栈为空。

Show - 方法返回DialogResult,因此您必须致电Pop以从堆栈中删除DialogResult

...
ilGenerator.EmitCall(OpCodes.Call, GetType(System.Windows.Forms.MessageBox).GetMethod("Show", {GetType(String)}), {GetType(String)})
ilGenerator.Emit(OpCodes.Pop) ' remove the return value of Show from the stack
ilGenerator.Emit(OpCodes.Ret)
...

尽管如此,您始终可以使用peverify来跟踪动态创建的程序集中的错误。

因此,在您的情况下,在SamAsm.exe上运行peverify会出现以下错误:

  

[IL]:错误:[c:\ yourpath \ SamAsm.exe:SamAsmType :: Main] [offset 0x0000000A]从void函数返回时,堆栈必须为空。   1个错误验证SamAsm.exe