1.編寫一個類文件在使用加載DLL文件的方法,這樣做的話,可以將第三方庫和本項目的dll分開存放不同的文件夾,管理程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
namespace test_interface{
public class DllInvoke
{
#region Win API
[DllImport("kernel32.dll")]
private extern static IntPtr LoadLibrary(string path);
[DllImport("kernel32.dll")]
private extern static IntPtr GetProcAddress(IntPtr lib, string funcName);
[DllImport("kernel32.dll")]
private extern static bool FreeLibrary(IntPtr lib);
#endregion
private IntPtr hLib;
//dll文件的路徑
public DllInvoke(String DLLPath)
{
hLib = LoadLibrary(DLLPath);
}
~DllInvoke()
{
FreeLibrary(hLib);
}
//将要执行的函数转换为委托
public Delegate Invoke (string APIName,Type t)
{
IntPtr api = GetProcAddress(hLib, APIName);
return (Delegate)Marshal.GetDelegateForFunctionPointer(api, t);
}
}
}
2.在form代碼上配置dll的物理路徑,為了方便管理開發的程序,將第三方庫單獨存放一個目錄,如lib目錄中在( exe文件運行根目錄下)
// 获取和设置包括该应用程序的目录的名称。
//System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase:如果在VS調試中,路徑為debug的路徑System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase:如果運行中(客戶環境中),路徑為exe文件根目錄的路徑
sFilePath =(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "lib\\CreateDLL.dll");
DllInvoke dll = new DllInvoke(sFilePath);
do_lps_func lps = (do_lps_func)dll.Invoke("do_lps", typeof(do_lps_func));