我正在尝试使用 DynamicMethod 调用非托管的类似 printf 的函数。在运行时我得到一个
BadImageFormatException:找不到索引。(来自 HRESULT 的异常:0x80131124)
这是运行时的限制还是我发出的代码是错误的?
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();
}
}