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