问题
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