c# - 如何发出静态外部方法?
问题描述
我正在尝试使用 P/Invoke 方法动态生成程序集。
这就是我现在正在做的事情:
var pinvoke = implementationBuilder.DefineMethod(methodInfo.Name,
MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.PinvokeImpl,
methodInfo.ReturnType,
parameters.Select(p => p.ParameterType).ToArray());
pinvoke.SetCustomAttribute(new CustomAttributeBuilder(DllImportCtor,
constructorArgs: new object[]{libraryPath},
namedFields: new []{CallingConventionField},
fieldValues: dllImportFieldValues));
但是,我得到“类型'...'中的方法'MethodName'没有实现。”
如何正确发出 C# 的用途[DllImport("42")] static extern void MethodName(IntPtr a);
?
解决方案
DefineMethod
只需将方法添加到类型。
您将改为使用TypeBuilder.DefinePInvokeMethod或其重载之一
定义一个 PInvoke 方法,给出它的名称、定义方法的 DLL 的名称、方法的属性、方法的调用约定、方法的返回类型、方法的参数类型以及PInvoke 标志。
例子
Type[] paramTypes = { typeof(int), typeof(string), typeof(string), typeof(int) };
MethodBuilder mb = tb.DefinePInvokeMethod(
methodName,
DllName,
MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.PinvokeImpl,
CallingConventions.Standard,
typeof(int),
paramTypes, // what ever you want here
CallingConvention.Winapi,
CharSet.Ansi);
参数类型
Type[]
方法参数的类型。
推荐阅读
- php - 如何将json响应数据转换为xml
- socialengine - 在社交引擎 php 中创建水平菜单
- java - Spring Boot 1.5.8 中的内存泄漏
- javascript - 使用 javascript 从数据库中使用 x 和 y 坐标绘制点
- excel - Excel 同一单元格中的两种类型的数据
- c# - VSTO Outlook 加载项:如何检查在重复窗口中标记了哪个单选按钮?
- javascript - AngularJS - 无水绑定
- javascript - momentjs 与时区的时间比较
- mongodb - 获取模板文件中的聚合查询结果(Handlebars)
- python-3.x - AWS:Lambda函数无法使用EC2实例的私有API调用rest api