Dynamic DLL call Method

Source: Internet
Author: User

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 );

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.