如何发出静态外部方法?

How do I emit static extern method?

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

但是,我得到 "Method 'MethodName' in type '...' does not have an implementation."

如何正确发出 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.