首页 > 解决方案 > 如何发出静态外部方法?

问题描述

我正在尝试使用 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);

标签: c#.netreflection.emit

解决方案


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[]方法参数的类型。


推荐阅读