4

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

1 回答 1

4

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

-MethodShow返回 a 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来跟踪动态创建的程序集中的错误。

因此,在您的情况下,运行 peverifySamAsm.exe会给您以下错误:

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

于 2012-12-03T15:15:32.363 回答