A project was created some time ago, requiring a DLL file developed by vc6 to be called. The file has multiple versions, so dynamic calling and uninstallation are supported.
After collecting some information about this, I wrote the following classes, which can conveniently call various types of DLL and are simple and practical.
Using system; <br/> using system. collections. generic; <br/> using system. text; <br/> using system. runtime. interopservices; </P> <p> namespace testdll <br/> {<br/> /// <summary> <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 ext Ern 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> // convert the function to be executed to the delegate <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/>}</P> <p>}
Write related proxies according to the commands in the DLL.
Public Delegate int msgbox (INT hwnd, string MSG, string CPP, int OK );
Public Delegate int deletefile (string MSG );
And then press the followingCodeJust do it.
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 );