我试图使用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();
}
}发布于 2015-04-24 10:49:57
虽然异常异常非常神秘,但我想它是由于与调用varargs方法相关的一些安全检查而引发的,或者可能是它们中的一个bug。有效的方法是提供逻辑关联的类型或模块:
var method = new DynamicMethod("printf", typeof(void), new Type[0], typeof(Program), true);那就完美无缺了。
https://stackoverflow.com/questions/29458616
复制相似问题