dimanche 25 octobre 2015

Create an .EXE thats Calls a function from a .dll

so i have a .dll with a function(static or instance, i can change it, and still works) and i want to create an Exe with a Main as entry point, that reads the command line, and calls the funcion from the .dll

-so i load the dll assembly, and get the type that has the function that i want

        Assembly asmLoaded = Assembly.LoadFrom(nameDLL);
        Type baseType = asmLoaded.GetType(typeName);

-Create the new assembly, module and type for the new Exe

AssemblyName aName = new AssemblyName("AppAsm");

        AssemblyBuilder ab =
        AppDomain.CurrentDomain.DefineDynamicAssembly(
            aName,
            AssemblyBuilderAccess.Save);

        ModuleBuilder mb =
        ab.DefineDynamicModule("AppMod", typeName + methodName + ".exe");

        TypeBuilder tb = mb.DefineType("AppType", TypeAttributes.Public);

-Get the methodInfo from the method that i wan to call, and its parameter Types[] for the later Emit(Opcodes.Call,..);

-Then i define the Method, "Main", to be the entry point

 MethodBuilder metb = tb.DefineMethod("Main", MethodAttributes.Public |
            MethodAttributes.Static, null, new Type[] { typeof(String[])});
 ab.SetEntryPoint(metb);

-By using ildasm, i tried to do this part, Generating the IL

 ILGenerator il = metb.GetILGenerator();
 for (int i = 0; i <paramTypes.Length; ++i)
        {
            il.Emit(OpCodes.Ldarg_0); // get the String[], in 0 cause its static
            il.Emit(OpCodes.Ldc_I4,i);
            il.Emit(OpCodes.Ldelem_Ref);
            il.Emit(OpCodes.Stloc, i);
        }         
        il.Emit(OpCodes.Ldloc, 0);
        il.Emit(OpCodes.Ldloc, 1);
        il.EmitCall(OpCodes.Call, wantedMethodInfo, paramTypes);
        il.Emit(OpCodes.Ret);

-finally i create the Type, and save the assemblyBuilder

tb.CreateType();
ab.Save(typeName + methodName + ".exe");

And of course it doesnt work, xD when i run the exe generated with some values, it throws System.InvalidProgramException: Common Languafe Runtime detected an invalid program. in AppTYpe.Main(String[] ) i think i should probably Pop, some stuff out of the stack, but not sure.





Aucun commentaire:

Enregistrer un commentaire