Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

It works with an array in which 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 constructor override has a method attribute, which 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 which throws me a VerificationException: (Just to assign a value to a pointer)

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

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

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

        //Can't use UnamangedExport as method attribute:
        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);
like image 287
Rafael Avatar asked Nov 24 '11 22:11

Rafael


1 Answers

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)

like image 108
Iridium Avatar answered Oct 14 '22 23:10

Iridium