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

I am making a sound synthesis program in which the user can create their own sounds by creating a node base layout, creating oscillators, filters, etc.

The program compiles the nodes into an intermediary language, which is then converted to MSIL through ILGenerator and DynamicMethod

It works with an array that stores all operations and data, but it will be faster if I can use pointers to let me do some bit-level operations later

PD: speed is very important!

I noticed that one override of the DynamicMethod constructor has a method attribute, which is UnsafeExport, but I cannot 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 (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); 
+6
source share
1 answer

If you pass the execution assembly 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 )

+5
source

Source: https://habr.com/ru/post/902338/


All Articles