c# - 如何发出静态外部方法?

标签 c# .net reflection.emit

我正在尝试使用 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或其重载之一

Defines a PInvoke method given its name, the name of the DLL in which the method is defined, the attributes of the method, the calling convention of the method, the return type of the method, the types of the parameters of the method, and the PInvoke flags.

示例

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

parameterTypes

Type[] The types of the method's parameters.

关于c# - 如何发出静态外部方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59004112/

相关文章:

c# - 跨域事件目录组成员

c# - 如何加载静态字段?

c# - Reflection.Emit 的性能损失

c# - 使用 Reflection.Emit 以编程方式为现有类属性添加新属性

c# - 使用 Microsoft.SqlServer.TransactSql.ScriptDom 生成查询

c# - 在 C# 中打开 Word 文档时显示修订气球

c# - 如何将 IHttpActionResult(内部带有 JSON)转换为我可以使用 LINQ 处理的对象

.net - ASP.NET MVC3 谷歌分析集成

c# - 将 ushort 图像转换为二进制?

c# - 我的线性算法的缺陷在哪里