關於動態調用Dll的方法

來源:互聯網
上載者:User

前段時間做了一個項目,其中要求調用一個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);   

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.