Question

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);
Was it helpful?

Solution

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top