ILGenerator:如何使用非托管指针? (我得到VerificationException)

时间:2011-11-24 22:41:55

标签: c# pointers unsafe dynamicmethod ilgenerator

我正在制作一个声音合成程序,用户可以创建自己的声音进行基于节点的合成,创建振荡器,滤波器等......

程序将节点编译成中间语言,然后通过ILGenerator和DynamicMethod将其转换为MSIL

它适用于存储所有操作和数据的数组,但如果我能够使用指针允许我稍后执行某些位操作,它会更快

PD:速度非常重要!!

我注意到一个DynamicMethod构造函数覆盖有一个方法属性,一个是UnsafeExport,但是我不能使用它,因为唯一有效的组合是Public + Static

这就是我想要做的事情,它会抛出一个VerificationException :(只是为指针赋值)

//Testing delegate
unsafe delegate float TestDelegate(float* data);

//Inside the test method (wich is marked as unsafe) 

        Type ReturnType = typeof(float);
        Type[] Args = new Type[] { typeof(float*) };

        //Can't use UnamangedExport as method atribute:
        DynamicMethod M = new DynamicMethod(
            "HiThere",
            ReturnType, Args);

        ILGenerator Gen = M.GetILGenerator();

        //Set the pointer value to 7.0:
        Gen.Emit(OpCodes.Ldarg_0);
        Gen.Emit(OpCodes.Ldc_R4, 7F);
        Gen.Emit(OpCodes.Stind_R4);

        //Just return a dummy value:
        Gen.Emit(OpCodes.Ldc_R4, 20F);
        Gen.Emit(OpCodes.Ret);



        var del = (TestDelegate)M.CreateDelegate(typeof(TestDelegate));

        float* data = (float*)Marshal.AllocHGlobal(4);
        //VerificationException thrown here:
        float result = del(data);

1 个答案:

答案 0 :(得分:5)

如果将正在执行的程序集ManifestModule作为第4个参数传递给DynamicMethod构造函数,它将按预期工作:

DynamicMethod M = new DynamicMethod(
    "HiThere",
    ReturnType, Args,
    Assembly.GetExecutingAssembly().ManifestModule);

(信用:http://srstrong.blogspot.com/2008/09/unsafe-code-without-unsafe-keyword.html