ILGenerator: How to use unmanaged pointers? (I get a VerificationException)

↘锁芯ラ 提交于 2019-12-21 16:25:45

问题


I'm making a sound synthesis program in wich the user can create his own sounds doing node-base compositing, creating oscillators, filters, etc...

The program compiles the nodes onto an intermediary language wich is then converted onto an MSIL via the ILGenerator and DynamicMethod

It works with an array in wich all operations and data are stored, but it will be faster if i was able to use pointers to allow me to do some bit-level operations later

PD: Speed is very important!!

I noticed that one DynamicMethod contructor override has a method atribute, wich one is UnsafeExport, but i can't use it, because the only valid combination is Public+Static

This is what i'm trying to do wich throws me a VerificationException: (Just to assign a value to a pointer)

//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:


If you pass the executing assembly's ManifestModule as the 4th parameter to the DynamicMethod constructor, it works as intended:

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

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



来源:https://stackoverflow.com/questions/8263146/ilgenerator-how-to-use-unmanaged-pointers-i-get-a-verificationexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!