public static T Register<T>(string dllName, string methodName, object[] parameters)
{
//COM has no Type class, so do the necessary conversions
Type returnType = typeof(T);
Type[] parameterTypes = new Type[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
{
parameterTypes[i] = parameters[i].GetType();
}
if (methodName == "VirtualProtect")
{
parameterTypes[parameters.Length - 1] = parameterTypes[parameters.Length - 1].MakeByRefType();
}
// Begin to build the dynamic assembly
AppDomain domain = AppDomain.CurrentDomain;
AssemblyName name = new System.Reflection.AssemblyName("PInvokeAssembly");
AssemblyBuilder assembly = domain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
ModuleBuilder module = assembly.DefineDynamicModule("PInvokeModule");
TypeBuilder type = module.DefineType("PInvokeType", TypeAttributes.Public | TypeAttributes.BeforeFieldInit);
// Define the actual P/Invoke method
MethodBuilder method = type.DefineMethod(methodName, MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Static | MethodAttributes.PinvokeImpl, returnType, parameterTypes);
// Apply the P/Invoke constructor
ConstructorInfo ctor = typeof(DllImportAttribute).GetConstructor(new Type[] { typeof(string) });
CustomAttributeBuilder attr = new System.Reflection.Emit.CustomAttributeBuilder(ctor, new Object[] { dllName });
method.SetCustomAttribute(attr);
// Create the temporary type, and invoke the method.
Type realType = type.CreateType();
return (T)realType.InvokeMember(methodName, BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, parameters);
}
IntPtr lib = Register<IntPtr>("kernel32.dll", "LoadLibrary",
new object[] { "fake.dll"});
C#动态构造调用原生dll
最新推荐文章于 2025-07-31 15:03:22 发布