Recently saw a classmate asked C # How to dynamically load C DLL, so here to share with you!

Source: Internet
Author: User

This article takes the VS2013 to do the development example, please be aware! (Note that the C # project only has the debug solution set, with the same change as release).

For example, the project is divided into 3:

Testdll is the export library, export the Test_hello function as the test DLL to be loaded;

Dynamicloaddemo the dynamic loading of C # dynamically loading DLLs; (Note: LoadLibrary, GetProcAddress, FreeLibrary)

Staticloaddemo is the way to load DLLs dynamically for static loading of C #. (Note: DllImport)

Testdll: Source Display

Testdll.h#pragma once#ifdef testdll_exports#define testdll_api  _declspec (dllexport) #else # define TESTDLL_API _ Declspec (dllimport) #endif #ifdef __cplusplusextern "C" {#endifTESTDLL_API int test_hello (); #ifdef __cplusplus}; #endif

  

Testdll.cpp#include "TestDLL.h" #ifdef __cplusplusextern "C" {#endifTESTDLL_API int Test_hello () {:: MessageBoxA (NULL, " Test_hello "," MSG ", 0); return 1;} #ifdef __cplusplus}; #endif

Through the above code, the function Test_hello is exported smoothly. Depends view as

Okay, here we go:

Dynamicloaddemo:

Use LoadLibrary, GetProcAddress, freelibrary three functions in C + + to enable dynamic DLL loading (unclear classmate please auto MSDN).

C # Dynamic load is also implemented with these 3 functions, but C # does not provide references to these functions, then we load the system DLL ourselves to get the call method of these three functions!

In fact, the method used is dllimport.

Such as

Here is the test code, the test project is very simple only a button, the code is as follows

      //int Test_hello ();         Public Delegate intTest_hello_fn (); Private voidLoad_click (Objectsender, EventArgs e) {Int32 hmodule=0; intIresult =0;  Do{hmodule= Cdynamicloadhelper.loadlibrary ("TestDLL.dll"); if(0==hmodule) {Iresult= -1;  Break; }                //IntPtr TEMP_FN =IntPtr.Zero; TEMP_FN= Cdynamicloadhelper.getprocaddress (hmodule,"Test_hello");//get C export Fun Test_hello                if(IntPtr.Zero = =TEMP_FN) {Iresult= -2;  Break; } TEST_HELLO_FN fn= (TEST_HELLO_FN) marshal.getdelegateforfunctionpointer (TEMP_FN,typeof(TEST_HELLO_FN)); Iresult=fn (); }  while(false); if(0!=hmodule)                {cdynamicloadhelper.freelibrary (hmodule); Hmodule=0; } MessageBox.Show ("test over result is:"+Iresult); }

Staticloaddemo:

Direct use of C # DllImport introduces a function, at this time the demo provides 2 test methods, one with exception capture, and the other without exception capture.

Load_catch_click (with abnormal seizures)
Load_click (no abnormal capture)
[DllImport ("TestDLL.dll", EntryPoint ="Test_hello")]         Public Static externInt32 test_hello_fn (); Private voidLoad_catch_click (Objectsender, EventArgs e) {            intIresult =0; Try{Iresult=Test_hello_fn (); }Catch{Iresult= -1; } MessageBox.Show ("test over result is:"+Iresult); }        Private voidLoad_click (Objectsender, EventArgs e) {             intIresult =Test_hello_fn (); MessageBox.Show ("test over result is:"+Iresult); }

The results are as follows:

DynamicLoadDemo.exe:

You can see the first pop-up of the Test_hello dialog box for the DLL, and the second dialog box is the C # result prompt box.

StaticLoadDemo.exe

(slightly) normally operating in the same condition as DynamicLoadDemo.exe (e.g.),

DLLs are normally loaded into the normal case. We do a special thing here, is to delete the current directory TestDLL.dll. What happens when you look at the operation?

DynamicLoadDemo.exe reflection normal no abnormal catch also found that the DLL does not exist, running results are expected. (No running fly)

StaticLoadDemo.exe

with abnormal seizures.

No abnormal seizures.

You can see the direct error without exception capture,

End of article! That kind of loading method also depends on the choice of everyone, I only stay in the demo level of C # do not evaluate that way more excellent!

SOURCE Package csdn:http://download.csdn.net/detail/u012251006/9912376

Some sources of information from the Internet! If you violate your rights, please let me know and I will delete them as soon as possible!

Recently saw a classmate asked C # How to dynamically load C DLL, so here to share with you!

Related Article

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.