静态调用
[DllImport(@"xxx.dll", EntryPoint = "TestMethod")]
static extern string TestMethod(string InParam);
string ret = TestMethod("hello");
动态调用
[DllImport("Kernel32.dll")]
public static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("kernel32.dll")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
[DllImport("kernel32.dll")]
public static extern bool FreeLibrary(IntPtr hModule);
private static IntPtr instance;//dll实例
public delegate string DlTestMethod(string InParam);//调用方法的委托
/// <summary>
/// 加载DLL
/// </summary>
/// <param name="dllPath"></param>
public static void LoadLib(string dllPath)
{
instance = LoadLibrary(dllPath);
if (instance == IntPtr.Zero)
{
Console.WriteLine("加载dll失败!");
}
}
/// <summary>
/// 获取方法指针
/// </summary>
/// <param name="functionName"></param>
/// <param name="t"></param>
/// <returns></returns>
private static Delegate GetAddress(string functionName, Type t)
{
IntPtr addr = GetProcAddress(instance, functionName);
if (addr == IntPtr.Zero)
return null;
else
return (Delegate)Marshal.GetDelegateForFunctionPointer(addr, t);
}
/// <summary>
/// 释放dlll
/// </summary>
public static void FreeLib()
{
FreeLibrary(instance);
}
LoadLib(@"xxx.dll");
DlTestMethod funcTestMethod = (DlTestMethod)GetAddress("TestMethod", typeof(DlTestMethod));
string ret = funcTestMethod("hello");
FreeLib();
总结
静态调用:调用方式简单,可满足通常的要求;被调用的dll会在程序加载时一起加载到内存中;如果在程序文件夹中没有dll文件,程序会报错。
动态调用:调用方式复杂,需借助于API函数来完成dll的加载,卸载及方法调用;能更加有效地使用内存,多在大型应用程序中使用;如果在程序文件夹中没有dll文件,也可以是程序不报错。