如何使用System.Reflection反射获取DllImportAttribute特性
通过反射获取DllImport特性信息的实现方法
- 初筛P/Invoke方法:可以先通过方法特性标记判断目标方法是否为外部P/Invoke实现,代码如下:
// myMethodInfo为已获取到的目标方法MethodInfo实例 bool isPInvokeMethod = (myMethodInfo.Attributes & MethodAttributes.PinvokeImpl) != 0;
- 注意踩坑:直接调用无参数的
GetCustomAttributes()方法拉取方法上所有特性时,返回集合中不会包含DllImportAttribute类型,必须显式指定要获取的特性类型才能正常读取。 - 核心读取代码:
using System.Reflection; using System.Runtime.InteropServices; // 显式指定获取DllImportAttribute类型 DllImportAttribute dllImport = (DllImportAttribute)myMethodInfo.GetCustomAttribute(typeof(DllImportAttribute)); if (dllImport != null) { // DllImport传入的原生库路径存储在Value属性中 string nativeDllPath = dllImport.Value; // 其余配置参数(如入口点名、字符集、调用约定、是否设置LastError等)均可直接通过DllImportAttribute对应属性读取 }
测试用的目标P/Invoke封装代码示例:
using System.Runtime.InteropServices; namespace MonoMac.foo { public class fooFramework { [DllImport ("/System/Library/Frameworks/foo")] public static extern void NSfoo (); } }
内容的提问来源于stack exchange,提问作者v1nce
相关产品推荐
相关产品推荐

