前段時間做了一個項目,其中要求調用一個VC6開發的Dll檔案,而該檔案有多個不同的版本,所以要支援動態調用,並支援卸載。
在收集了一些這方面的資料後,編寫了下面的類,該類可以方便的調用各種類型的dll,而且簡單實用。
using System;<br />using System.Collections.Generic;<br />using System.Text;<br />using System.Runtime.InteropServices;</p><p>namespace testdll<br />{<br /> /// <summary><br /> ///<br /> /// </summary><br /> class InvokeDll<br /> {<br /> #region Win API<br /> [DllImport("kernel32.dll")]<br /> private extern static IntPtr LoadLibrary(string path);</p><p> [DllImport("kernel32.dll")]<br /> private extern static IntPtr GetProcAddress(IntPtr lib, string funcName);</p><p> [DllImport("kernel32.dll")]<br /> private extern static bool FreeLibrary(IntPtr lib);<br /> #endregion</p><p> private IntPtr hLib;<br /> public InvokeDll(String DLLPath)<br /> {<br /> hLib = LoadLibrary(DLLPath);<br /> }</p><p> ~InvokeDll()<br /> {<br /> FreeLibrary(hLib);<br /> }</p><p> //將要執行的函數轉換為委託<br /> public Delegate Invoke (string APIName,Type t)<br /> {<br /> IntPtr api = GetProcAddress(hLib, APIName);<br /> if (api == IntPtr.Zero)<br /> return null;<br /> else<br /> return Marshal.GetDelegateForFunctionPointer(api, t);<br /> }<br />}</p><p> }
使用時,先根據dll中的命令寫出相關的代理
public delegate int MsgBox(int hwnd,string msg,string cpp,int ok);
public delegate int DeleteFile(string msg);
然後按下面的代碼做就可以了。
InvokeDll dll = new InvokeDll("user32.dll");<br />MsgBox mymsg = (MsgBox)dll.Invoke("MessageBoxA", typeof(MsgBox));<br />mymsg(this.Handle.ToInt32(), "txtmsg", "titleText", 64);</p><p>InvokeDll dll1 = new InvokeDll("kernel32.dll");<br />DeleteFile df= (DeleteFile)dll1.Invoke("DeleteFileA", typeof(DeleteFile));<br />df(deletedfilename);