gpt4 book ai didi

c# - ILGenerator:如何使用非托管指针? (我得到一个 VerificationException)

转载 作者:太空狗 更新时间:2023-10-29 21:41:09 26 4
gpt4 key购买 nike

我正在制作一个声音合成程序,用户可以在其中通过基于节点的合成、创建振荡器、滤波器等来创建自己的声音。

程序将节点编译成中间语言,然后通过 ILGenerator 和 DynamicMethod 将其转换成 MSIL。

它使用一个存储所有操作和数据的数组,但如果我能够使用指针允许我稍后执行一些位级操作,它会更快。

PD:速度很重要!

我注意到一个 DynamicMethod 构造函数覆盖有一个方法属性,其中一个是 UnsafeExport,但我不能使用它,因为唯一有效的组合是 Public+Static

这就是我正在尝试做的事情,它会抛出一个 VerificationException:(只是为指针赋值)

//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);

最佳答案

如果将执行程序集的 ManifestModule 作为第四个参数传递给 DynamicMethod 构造函数,它会按预期工作:

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

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

关于c# - ILGenerator:如何使用非托管指针? (我得到一个 VerificationException),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8263146/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com