Calling the varargs method via DynamicMethod

I am trying to call an unmanaged function like printf using DynamicMethod. At runtime, I get

BadImageFormatException: Index not found. (Exception from HRESULT: 0x80131124)

Is this a run-time limit, or is my emitted code incorrect?

public class Program { [DllImport("msvcrt40.dll",CallingConvention = CallingConvention.Cdecl)] public static extern int printf(string format, __arglist); static void Main(string[] args) { var method = new DynamicMethod("printf", typeof(void), new Type[0], true); var il = method.GetILGenerator(); il.Emit(OpCodes.Ldstr, " %s=%d\n"); il.Emit(OpCodes.Ldstr, "a"); il.Emit(OpCodes.Ldc_I4_0); il.EmitCall(OpCodes.Call, typeof(Program).GetMethod("printf", BindingFlags.Public | BindingFlags.Static), new Type[] { typeof(string), typeof(int) }); il.Emit(OpCodes.Pop); il.Emit(OpCodes.Ret); var action = (Action)method.CreateDelegate(typeof(Action)); action.Invoke(); } } 
+6
source share
1 answer

Although the exception is extremely cryptic, I assume that it was thrown due to some security checks related to calling the varargs method, or it could be a bug in them. What works to provide a logically related type or module:

 var method = new DynamicMethod("printf", typeof(void), new Type[0], typeof(Program), true); 

It works flawlessly.

+4
source

Source: https://habr.com/ru/post/984705/


All Articles