資源描述:
《C#動(dòng)態(tài)調(diào)用Dll的開發(fā)方法.doc》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在教育資源-天天文庫。
1、關(guān)于C#動(dòng)態(tài)調(diào)用Dll的開發(fā)方法前段時(shí)間做了一個(gè)項(xiàng)目,其中要求調(diào)用一個(gè)VC6開發(fā)的Dll文件,而該文件有多個(gè)不同的版本,所以要支持動(dòng)態(tài)調(diào)用,并支持卸載。在收集了一些這方面的資料后,編寫了下面的類,該類可以方便的調(diào)用各種類型的dll,而且簡(jiǎn)單實(shí)用。[c-sharp]?viewplaincopy1.using?System;??2.using?System.Collections.Generic;??3.using?System.Text;??4.using?System.Runtime.InteropServices
2、;??5.??6.namespace?testdll??7.{??8.????///???9.????///???10.????///???11.????class?InvokeDll??12.????{??13.????????#region?Win?API??14.????????[DllImport("kernel32.dll")]??15.????????private?extern?static?IntPtr?LoadLibrary(string?path);??16
3、.??17.????????[DllImport("kernel32.dll")]??18.????????private?extern?static?IntPtr?GetProcAddress(IntPtr?lib,?string?funcName);??19.??20.????????[DllImport("kernel32.dll")]??21.????????private?extern?static?bool?FreeLibrary(IntPtr?lib);??22.????????#endregion?
4、?23.??24.????????private?IntPtr?hLib;??25.????????public?InvokeDll(String?DLLPath)??26.????????{??27.????????????hLib?=?LoadLibrary(DLLPath);??28.????????}??29.??30.????????~InvokeDll()??1.????????{??2.????????????FreeLibrary(hLib);??????????????3.????????}??4
5、.??5.????????//將要執(zhí)行的函數(shù)轉(zhuǎn)換為委托??6.????????public?Delegate?Invoke?(string?APIName,Type?t)????7.????????{??8.????????????IntPtr?api?=?GetProcAddress(hLib,?APIName);??9.????????????if?(api?==?IntPtr.Zero)??10.????????????????return?null;??11.????????????else??12.???
6、?????????????return?Marshal.GetDelegateForFunctionPointer(api,?t);??13.????????}??14.}??15.??16.????}???使用時(shí),先根據(jù)dll中的命令寫出相關(guān)的代理publicdelegateintMsgBox(inthwnd,stringmsg,stringcpp,intok);publicdelegateintDeleteFile(stringmsg);然后按下面的代碼做就可以了。[c-sharp]?viewplaincopy
7、1.InvokeDll?dll?=?new?InvokeDll("user32.dll");??2.MsgBox?mymsg?=?(MsgBox)dll.Invoke("MessageBoxA",?typeof(MsgBox));??3.mymsg(this.Handle.ToInt32(),?"txtmsg",?"titleText",?64);??4.??5.??6.InvokeDll?dll1?=?new?InvokeDll("kernel32.dll");??7.DeleteFile?df=?(Delete
8、File)dll1.Invoke("DeleteFileA",?typeof(DeleteFile));??8.df(deletedfilename);