如何通过反射构造函数指针类型?及用Reflection.Emit创建指定字段
构造特定签名的函数指针类型及Reflection.Emit字段创建方案
一、正确构造函数指针Type的方法
你之前的代码报错是因为使用了错误的开放泛型类型delegate*<>,函数指针的泛型参数需要包含所有参数类型 + 返回值类型,且要对应参数数量选择匹配的开放泛型类型:
- 对于1个参数的函数指针(如
int(int)),对应开放泛型类型是delegate*<,>(两个类型参数:参数类型、返回值类型) - 对于2个参数的函数指针(如
string(int, bool)),对应开放泛型类型是delegate*<,,>(三个类型参数:参数1类型、参数2类型、返回值类型)
示例代码(构造int(int)的函数指针类型):
// 参数类型 + 返回值类型:顺序为[参数类型, 返回值类型] Type[] typeArgs = [typeof(int), typeof(int)]; // 获取匹配参数数量的开放函数指针类型 Type openFuncPtrType = typeof(delegate*<,>); Type functionPointerType = openFuncPtrType.MakeGenericType(typeArgs);
如果需要通用处理任意参数数量的场景,可以通过动态生成对应开放泛型类型的方式:
Type[] parameterTypes = [typeof(int), typeof(bool)]; // 自定义参数列表 Type returnType = typeof(string); // 自定义返回类型 // 拼接泛型参数数组:参数在前,返回值在后 Type[] allTypeArgs = new Type[parameterTypes.Length + 1]; Array.Copy(parameterTypes, allTypeArgs, parameterTypes.Length); allTypeArgs[parameterTypes.Length] = returnType; // 根据参数数量生成对应的开放函数指针类型名称 string openTypeFullName = $"System.Runtime.CompilerServices.Delegate*{new string(',', allTypeArgs.Length - 1)}"; Type openFuncPtrType = Type.GetType(openTypeFullName)!; Type functionPointerType = openFuncPtrType.MakeGenericType(allTypeArgs);
二、用Reflection.Emit创建目标字段
如果你的最终需求是生成int32 *(int32)类型的字段,直接使用ModuleBuilder.GetFunctionPointerType会更简洁,无需手动构造泛型类型:
// 假设已通过AssemblyBuilder创建了ModuleBuilder实例 ModuleBuilder moduleBuilder = ...; // 定义函数指针的签名:返回值int,参数int Type returnType = typeof(int); Type[] parameterTypes = [typeof(int)]; // 获取函数指针类型 Type funcPtrType = moduleBuilder.GetFunctionPointerType(returnType, parameterTypes); // 定义类型并添加字段 TypeBuilder typeBuilder = moduleBuilder.DefineType("MyType", TypeAttributes.Public); FieldBuilder fieldBuilder = typeBuilder.DefineField( "function", funcPtrType, FieldAttributes.Public ); // 完成类型创建 Type createdType = typeBuilder.CreateType();
生成的字段会符合你需要的.field public method int32 *(int32) function格式。
内容的提问来源于stack exchange,提问作者Jonas _
相关产品推荐
相关产品推荐

