VC ++ dynamic link library (DLL) programming (II)

Source: Internet
Author: User
Tags export class types of functions

The previous section introduced the debugging and viewing of static link libraries (dynamic link library (DLL) programming in simple terms (I). This section mainly introduces non-MFC DLL.

4. Non-MFC DLL

4.1 A simple DLL

Section 2nd describes how to provide the Add function interface using the static Link Library. Next we will look at how to use the dynamic link library to implement the Add function with the same function.

6. Create a Win32 dynamic-Link Library Project dlltest in VC ++ (Click here to download the attachment of this project ). Be sure not to select the MFC Appwizard (DLL), because the MFC dynamic link library to be described in sections 5th and 6 will be created using the MFC Appwizard (DLL.

Figure 6 create a non-MFC DLL

Add the Lib. h and Lib. cpp files to the created Project. The source code is as follows:

/* File name: Lib. H */

# Ifndef lib_h

# Define lib_h

Extern "C" int _ declspec (dllexport) add (int x, int y );

# Endif

/* File name: Lib. cpp */

# Include "Lib. H"

Int add (int x, int y)

{

Return X + Y;

}

Similar to the call to the static Link Library in section 2nd, we also set up an application project dllcall in the same workspace as the DLL project, which calls the function add in the DLL. Its source code is as follows:

# Include <stdio. h>

# Include <windows. h>

Typedef int (* lpaddfun) (INT, INT); // macro-defined function pointer type

Int main (INT argc, char * argv [])

{

Hinstance hdll; // DLL handle

Lpaddfun addfun; // function pointer

Hdll = loadlibrary (".. // debug // dlltest. dll ");

If (hdll! = NULL)

{

Addfun = (lpaddfun) getprocaddress (hdll, "add ");

If (addfun! = NULL)

{

Int result = addfun (2, 3 );

Printf ("% d", result );

}

Freelibrary (hdll );

}

Return 0;

}

Analyze the above Code, Lib in the dlltest project. the CPP file is the same as the static Link Library version in section 2nd. The difference is that Lib. h added the _ declspec (dllexport) statement before the function add statement. This statement declares that the function add is the DLL export function. There are two types of functions in the DLL:

(1) DLL export function, which can be called by a program;

(2) DLL internal functions can only be used in DLL programs, and applications cannot call them.

While the application calls this DLL and calls the static Link Library in section 2nd are quite different. Next we will analyze them one by one.

First, the statement typedef int (* lpaddfun) (INT, INT) defines a function pointer type that is the same as that accepted by the Add function and returned values. Then, the instance addfun of lpaddfun is defined in the main function;

Secondly, a DLL hinstance handle instance hdll is defined in function main. The DLL module is dynamically loaded through the Win32 API function loadlibrary and the DLL module handle is assigned to hdll;

Again, in the main function, use the Win32 API function getprocaddress to obtain the address of function add in the loaded DLL module and assign it to addfun. The function pointer addfun is used to call the Add function in the DLL;

Finally, after the application project uses the DLL, the function main releases the loaded DLL module through the Win32 API function freelibrary.

Through this simple example, we know the general concepts of DLL definition and calling:

(1) The dll must declare the export function (or variable or class) in a specific way );

(2) The application project must call the DLL export function (or variable or class) in a specific way ).

Next we will elaborate on the "specific method.
4.2 declare the export Function

There are two ways to export the function declaration in dll: one is to add _ declspec (dllexport) in the function declaration given in section 4.1; another way is to use the module definition (. def) file declaration ,. the def file provides the linker with information about export, attributes, and other aspects of the linked program.

The following code demonstrates how to declare function Add as a DLL export function in the same. Def file (the Lib. Def file must be added to the dlltest project ):

; LIB. Def: Export DLL Functions

Library dlltest

Exports

Add @ 1

The. Def file rules are as follows:

(1) The Library statement describes the DLL corresponding to the. Def file;

(2) Name of the function to be exported after the exports statement. You can add @ n after the export function name in the. Def file to indicate that the sequence number of the function to be exported is n (this sequence number will play its role during function calling );

(3) The annotation in the def file is specified by the semicolon (;) at the beginning of each comment line, and the comment cannot share a line with the statement.

In this example, the Lib. Def file is used to generate a dynamic link library named "dlltest", export the Add function, and specify the serial number of the add function as 1.

4.3 DLL call Method

In the example in section 4.1, we see the trinity "DLL load-DLL function address acquisition-DLL release" method provided by the "loadlibrary-getprocaddress-freelibrary" system API, this call method is called DLL dynamic call.

Dynamic calling is characterized by API functions used by programmers to load and uninstall DLL files. programmers can determine when or not to load DLL files. explicit links determine which DLL file to load during runtime.

The static call method corresponds to the dynamic call method, and the "Dynamic and Static" method comes from the opposition and unity of the material world. The opposition and unification of "Dynamic and Static" have been verified countless times in technical fields, such as static IP and DHCP, Static Routing and dynamic routing. As we have known from the past, libraries are also divided into static libraries and dynamic library DLL. unexpectedly, the calling methods of libraries are also divided into static and dynamic. "Dynamic and Static" is everywhere. Zhou Yi has realized that there must be a static dynamic and static dynamic balance view, and "Yi. Department of Speech" said: "the dynamic and static, flexible and broken ". Philosophy means a universal truth, so we can often see the shadows of philosophy in the boring technical field.

Static calling is characterized by the completion of DLL loading by the compilation system and the uninstallation of DLL at the end of the application. When the application that calls a DLL ends, if other programs in the system use the DLL, Windows will subtract 1 from the DLL application record, it is not released until all programs that use the DLL end. The static call method is simple and practical, but it is not as flexible as the dynamic call method.

Next, let's take a look at the static call example (Click here to download the attachment of this project) and compile the generated by the dlltest project. lib and. the DLL file is written to the path of the dllcall project, and dllcall executes the following code:

# Pragma comment (Lib, "dlltest. lib ")

// The. Lib file only contains information about the Function relocation in the corresponding DLL file.

Extern "C" _ declspec (dllimport) add (int x, int y );

Int main (INT argc, char * argv [])

{

Int result = add (2, 3 );

Printf ("% d", result );

Return 0;

}

From the code above, we can see that the smooth execution of static call methods requires two actions:

(1) Tell the compiler the path and file name of the. Lib file corresponding to the DLL, and # pragma comment (Lib, "dlltest. lib") serves this purpose.

When a programmer creates a DLL file, the connector automatically generates a corresponding one. lib file, which contains the symbolic name and serial number of the DLL export function (excluding the actual code ). In an application, the. Lib file is used as a DLL replacement file for compilation.

(2) declare the import function. The _ declspec (dllimport) in the extern "C" _ declspec (dllimport) add (int x, int y) Statement plays this role.

The static call method does not need to use system APIs to load or uninstall the DLL and obtain the address of the exported function in the DLL. This is because, when programmers compile an application through static links. function symbols matching the exported characters in the Lib file will enter the generated EXE file ,. the file name of the corresponding DLL file contained in the Lib file is also stored in the EXE file by the compiler. When a DLL file needs to be loaded while the application is running, Windows will find and load the DLL based on the information, and then use the symbolic name to implement dynamic links to the DLL function. In this way, exe can directly call the DLL output function through the function name, just like calling other functions in the program.

4.4 dllmain Function

Windows requires an entry function when loading DLL, just as the console or DOS program requires the main function and Win32 program requires the winmain function. In the previous example, the DLL does not provide the dllmain function, and the application project can also reference the DLL. This is because Windows cannot find the dllmain function, the system will introduce a default dllmain function version from other runtime libraries without any operation. This does not mean that the DLL can discard the dllmain function.

According to the writing specifications, windows must find and execute the dllmain function in the DLL as the basis for loading the DLL, which allows the DLL to be kept in the memory. This function is not an export function, but an internal function of the DLL. This means that you cannot directly reference the dllmain function in the application project. dllmain is automatically called.

Let's look at an example of the dllmain function (Click here to download the attachment of this project ).

Bool apientry dllmain (handle hmodule,

DWORD ul_reason_for_call,

Lpvoid lpreserved

)

{

Switch (ul_reason_for_call)

{

Case dll_process_attach:

Printf ("/nprocess attach of DLL ");

Break;

Case dll_thread_attach:

Printf ("/nthread attach of DLL ");

Break;

Case dll_thread_detach:

Printf ("/nthread detach of DLL ");

Break;

Case dll_process_detach:

Printf ("/nprocess detach of DLL ");

Break;

}

Return true;

}

The dllmain function is called when the DLL is loaded and detached. When a single thread starts and stops, the dllmain function is also called. ul_reason_for_call indicates the reason for the call. There are four causes, namely process_attach, process_detach, thread_attach, and thread_detach, which are listed in the switch statement.

Let's take a closer look at the dllmain function header bool apientry dllmain (handle hmodule, word ul_reason_for_call, lpvoid lpreserved ).

Apientry is defined as _ stdcall, which means that this function is called in the standard Pascal method, that is, the winapi method;

Each DLL module in a process is identified by a globally unique 32-byte hinstance handle and only valid within a specific process. The handle represents the starting address of the DLL module in the process virtual space. In Win32, the values of hinstance and hmodule are the same. You can replace these two types. This is the origin of the function parameter hmodule.

Run the following code:

Hdll = loadlibrary (".. // debug // dlltest. dll ");

If (hdll! = NULL)

{

Addfun = (lpaddfun) getprocaddress (hdll, makeintresource (1 ));

// Makeintresource directly uses the serial number in the exported file

If (addfun! = NULL)

{

Int result = addfun (2, 3 );

Printf ("/ncall add in dll: % d", result );

}

Freelibrary (hdll );

}

The output sequence is as follows:

Process attach of DLL

Call add in dll: 5

Process detach of DLL

This output sequence verifies the time when dllmain is called.

The getprocaddress (hdll, makeintresource (1) in the Code is worth noting. in the def file, the sequence number specified by the Add function is used to access the Add function. It is embodied in makeintresource (1). makeintresource is a macro that obtains the function name through the sequence number and is defined as (Excerpted from winuser. h ):

# Define makeintresourcea (I) (lpstr) (DWORD) (Word) (I )))

# Define makeintresourcew (I) (lpwstr) (DWORD) (Word) (I )))

# Ifdef Unicode

# Define makeintresource makeintresourcew

# Else

# Define makeintresource makeintresourcea

4.5 _ stdcall conventions

If a DLL written in VC ++ is to be called by a program written in other languages, the function call method should be declared as _ stdcall. winapi adopts this method, the default call method of C/C ++ is _ cdecl. The _ stdcall method is different from the _ cdecl method for generating symbols for function names. If the C compilation method is used (the function must be declared as extern "C" in C ++), __stdcall indicates that the name of the output function must be underlined, the symbol "@" is followed by the number of bytes of the parameter, in the form of _ functionname @ number. The call Convention of _ cdecl is to only underline the name of the output function, in the form of _ functionname.

In Windows programming, macros of common function types are related to _ stdcall and _ cdecl (Excerpted from windef. h ):

# Define callback _ stdcall // This is the legendary callback function.

# Define winapi _ stdcall // This is the legendary winapi

# Define winapiv _ cdecl

# Define apientry winapi // The dllmain entry is here

# Define apiprivate _ stdcall

# Define Pascal _ stdcall

In Lib. H, the Add function should be declared as follows:

Int _ stdcall add (int x, int y );

In the Application project, the function pointer type should be defined:

Typedef int (_ stdcall * lpaddfun) (INT, INT );

In Lib. h declares the function as _ stdcall, while typedef int (* lpaddfun) (INT, INT) is still used in the application project. An error will occur during runtime (because the type does not match, in the Application project, it is still the default _ cdecl call). The Dialog Box 7 is displayed.

Figure 7 running errors when the call conventions do not match

The section in Figure 8 actually shows the cause of the error, that is, "this is usually a result ...".

Click here to download the source code attachment of the _ stdcall call example project.

4.6 DLL export Variables

DLL-defined global variables can be accessed by the calling process; dll can also access the global data of the calling process, let's take a look at the example of referencing the variable in DLL in the Application Project (Click here to download the attachment of this project ).

 

/* File name: Lib. H */

# Ifndef lib_h

# Define lib_h

Extern int dllglobalvar;

# Endif

/* File name: Lib. cpp */

# Include "Lib. H"

# Include <windows. h>

Int dllglobalvar;

Bool apientry dllmain (handle hmodule, DWORD ul_reason_for_call, lpvoid lpreserved)

{

Switch (ul_reason_for_call)

{

Case dll_process_attach:

Dllglobalvar = 100; // when the DLL is loaded, assign a global variable of 100

Break;

Case dll_thread_attach:

Case dll_thread_detach:

Case dll_process_detach:

Break;

}

Return true;

}

; File name: Lib. Def

; Export variables in DLL

Library "dlltest"

Exports

Dllglobalvar constant

; Or dllglobalvar data

Getglobalvar

We can see from LIB. h and Lib. cpp that the definition and usage of global variables in DLL are the same as that in general programming. To export a global variable, we need to add the following after the exports of the. Def file:

Variable name constant // outdated method

Or

Variable name data // New Method prompted by VC ++

Reference the global variables defined in DLL in the main function:

# Include <stdio. h>

# Pragma comment (Lib, "dlltest. lib ")

Extern int dllglobalvar;

Int main (INT argc, char * argv [])

{

Printf ("% d", * (int *) dllglobalvar );

* (Int *) dllglobalvar = 1;

Printf ("% d", * (int *) dllglobalvar );

Return 0;

}

Note that the use of extern int dllglobalvar declares that the imported global variable is not the DLL itself, but its address. The application must use the global variable in the DLL through forced pointer conversion. This can be seen from * (int *) dllglobalvar. Therefore, when using this method to reference DLL global variables, do not assign values as follows:

Dllglobalvar = 1;

The result is that the content of the dllglobalvar pointer changes, and the global variables in the DLL cannot be referenced in the program.

A better way to reference global variables in DLL in an application project is:

# Include <stdio. h>

# Pragma comment (Lib, "dlltest. lib ")

Extern int _ declspec (dllimport) dllglobalvar; // use _ declspec (dllimport) to import

Int main (INT argc, char * argv [])

{

Printf ("% d", dllglobalvar );

Dllglobalvar = 1; // this can be used directly, without the need for forced pointer Conversion

Printf ("% d", dllglobalvar );

Return 0;

}

The _ declspec (dllimport) method imports the global variables in the DLL instead of their addresses. I suggest using this method whenever possible.

4.7 DLL export class

Classes defined in dll can be used in application projects.

In the following example, we define the point and circle classes in the DLL and reference them in the application project (Click here to download the attachment of this project ).

// File name: Declaration of the point. h and point classes

# Ifndef point_h

# Define point_h

# Ifdef dll_file

Class _ declspec (dllexport) Point // export Class Point

# Else

Class _ declspec (dllimport) Point // import Class Point

# Endif

{

Public:

Float y;

Float X;

Point ();

Point (float x_coordinate, float y_coordinate );

};

# Endif

// File name: Implementation of Point. cpp and Point class

# Ifndef dll_file

# Define dll_file

# Endif

# Include "point. H"

// Default constructor of the Class Point

Point: Point ()

{

X = 0.0;

Y = 0.0;

}

// Point-like Constructor

Point: Point (float x_coordinate, float y_coordinate)

{

X = x_coordinate;

Y = y_coordinate;

}

// File name: Statement of the circle. h and circle classes

# Ifndef circle_h

# Define circle_h

# Include "point. H"

# Ifdef dll_file

Class _ declspec (dllexport) circle // export class circle

# Else

Class _ declspec (dllimport) circle // import class circle

# Endif

{

Public:

Void setcentre (const point multicast repoint );

Void setradius (float R );

Float getgirth ();

Float getarea ();

Circle ();

PRIVATE:

Float radius;

Point center;

};

# Endif

// File name: Implementation of the circle. cpp and circle classes

# Ifndef dll_file

# Define dll_file

# Endif

# Include "circle. H"

# Define PI 3.1415926

// Constructor of the circle class

Circle: Circle ()

{

Center = point (0, 0 );

Radius = 0;

}

// Obtain the area of the circle

Float circle: getarea ()

{

Return pI * radius;

}

// Obtain the circle perimeter

Float circle: getgirth ()

{

Return 2 * pI * radius;

}

// Set the coordinates of the center

Void circle: setcentre (const point duplicate repoint)

{

Center = Centrepoint;

}

// Set the circle radius

Void circle: setradius (float R)

{

Radius = R;

}

Class reference:

# Include "../circle. H" // contains the class declaration header file

# Pragma comment (Lib, "dlltest. lib ");

Int main (INT argc, char * argv [])

{

Circle C;

Point P (2.0, 2.0 );

C. setcentre (P );

C. setradius (1.0 );

Printf ("Area: % F girth: % F", C. getarea (), C. getgirth ());

Return 0;

}

From the source code above, we can see that the macro dll_file is defined in the DLL class implementation code, so the class declaration contained in the DLL implementation is actually:

Class _ declspec (dllexport) Point // export Class Point

{

...

}

And

Class _ declspec (dllexport) circle // export class circle

{

...

}

Dll_file is not defined in the application project, so the class declaration introduced after point. h and circle. H is:

Class _ declspec (dllimport) Point // import Class Point

{

...

}

And

Class _ declspec (dllimport) circle // import class circle

{

...

}

Yes, it is through the DLL

Class _ declspec (dllexport) class_name // export class circle

{

...

}

And

Class _ declspec (dllimport) class_name // import class

{

...

}

To export and import classes!

We usually use a macro in the class declaration header file to compile it into the class _ declspec (dllexport) class_name or class _ declspec (dllimport) class_name version, so that two header files are no longer required. This program uses:

# Ifdef dll_file

Class _ declspec (dllexport) class_name // export class

# Else

Class _ declspec (dllimport) class_name // import class

# Endif

In fact, in the description of the mfc dll, you will see a simpler method than this, and here only to illustrate the problems of the _ declspec (dllexport) and _ declspec (dllimport) pairs.

It can be seen that almost everything in the DLL can be seen in the application project, including functions, variables, and classes. This is the powerful capability provided by the DLL. As long as the DLL releases these interfaces, the application will use it as it uses the program in this project!

Although this chapter uses VC ++ as a platform to explain non-mfc dll, these general concepts are the same in other languages and development environments, and their ways of thinking can be directly transitioned.

Next, we willResearch on the MFC rule DLL (To be continued ...)

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.