从非托管 DLL 动态调用






3.44/5 (9投票s)
2005年1月4日

93591

1
本文档解释了如何从 C# 调用非托管 DLL 函数。
引言
本文演示了如何从 C# 代码调用一个非托管 MFC DLL 函数。代码使用了 Reflection
命名空间。要使用下面的代码片段,您必须添加以下内容
using System.Reflection.Emit;
using System.Reflection;
假设您有一个 MFC DLL(getmyversion.dll),其中包含一个名为 int GetDllversion(char* verstr)
的函数,该函数将您的 DLL 版本返回到 verstr
中。
下面的函数创建了一个动态程序集对象。DefinePInvokeMethod
方法创建了一个我们将用于访问我们的 DLL 函数的方法。为了完成我们动态模块的全局操作,调用 CreateGlobalFunctions
。使用我们先前创建的方法的 GetMethod
函数,我们可以调用我们的 MFC DLL 函数。
public object DynamicDllFunctionInvoke( string DllPath, string EntryPoint )
{
// Version string definition
byte[] verstr = new byte[1024];
//Define return type of your dll function.
Type returnType = typeof(int);
//out or in parameters of your function.
Type [] parameterTypes = {typeof(byte[])};
object[] parameterValues = {verstr};
string entryPoint = entrypoint;
// Create a dynamic assembly and a dynamic module
AssemblyName asmName = new AssemblyName();
asmName.Name = "tempDll";
AssemblyBuilder dynamicAsm =
AppDomain.CurrentDomain.DefineDynamicAssembly(asmName,
AssemblyBuilderAccess.Run);
ModuleBuilder dynamicMod =
dynamicAsm.DefineDynamicModule("tempModule");
// Dynamically construct a global PInvoke signature
// using the input information
MethodBuilder dynamicMethod = dynamicMod.DefinePInvokeMethod(
entryPoint, DllPath, MethodAttributes.Static | MethodAttributes.Public
| MethodAttributes.PinvokeImpl , CallingConventions.Standard,
returnType, parameterTypes, CallingConvention.Winapi,
CharSet.Ansi);
// This global method is now complete
dynamicMod.CreateGlobalFunctions();
// Get a MethodInfo for the PInvoke method
MethodInfo mi = dynamicMod.GetMethod(EntryPoint);
// Invoke the static method and return whatever it returns
object retval = mi.Invoke(null, parameterValues);
// Filled verstr paramter.
MessageBox.Show(System.Text.ASCIIEncoding.ASCII.GetString(verstr));
return retval;
}
该方法的示例调用如下
DynamicDllFunctionInvoke(@"c:\getmyversion.dll","GetDllVersion");