In DLL calls written in C/C ++, loadlibrary is sometimes used to load dynamic link libraries. In this case, the functions we need to call must be obtained through getprocaddress. In many cases, before loading, we need to define the pointer of the function, then define a function variable, and then forcibly convert the pointer value obtained by getprocaddress to the pointer we need. As shown in the following code: 1 typedef int (* Add) (int m, int N );
2
3 handle hdll = loadlibrary ("Your. dll ");
4 Add add;
5 If (null! = Hdll)
6 {
7 add = (ADD) getprocaddress ("add ");
8
9 // other code
10}
However, if you write the code in the following way, you can reduce some code input and do not need to add a typedef type for each function. After all, every function is unique, so the code can be written as follows: 1 int (winapi * lpadd) (int m, int N );
2
3 handle hdll = loadlibrary ("Your. dll ");
4 If (null! = Hdll)
5 {
6 (farproc) lpadd = getprocaddress ("add ");
7
8 // other code
9}
Every variable that needs to be copied using getprocaddress is forcibly defined using (farproc), and lpadd will be a global variable and can be used anywhere.
If the Lib file is not provided, you can use the following method to display the Lib function, and this method can be dynamically loaded, so it is more flexible than Lib:
1 int (winapi * lpadd) (int m, int N );
2
3 static int iloadnum = 0; // static will not spread to other files
4 static handle hdll = NULL;
5
6 bool loadyourdll ()
7 {
8 If (null = hdll)
9 {
10 hdll = loadlibrary ("Your. dll ");
11}
12
13 if (null = hdll)
14 {
15 return false;
16}
17
18 if (0 = iloadnum)
19 {
20 (farproc) lpadd = getprocaddress (hdll, "add ");
21}
22
23 iloadnum ++;
24 return true;
25}
26
27 int freeyourdll ()
28 {
29 iloadnum --;
30
31 if (iloadnum = 0)
32 {
33 freelibrary (hdll );
34 hdll = NULL;
35}
36 return iloadnum;
37}
38
39 int add (int m, int N)
40 {
41 // loadyourdll ();
42 int ret = lpadd (m, n );
43 // freeyourdll ();
44 return ret;
45}
46
If you use this method to compile the DLL call file, call the loadyourdll () function where the DLL needs to be loaded, then, you can directly use the Add function in the same way as using the Lib file to apply the function in the DLL, And the name is not changed, which makes it easier to transplant, if loadyourdll and freeyourdll are encapsulated as a class of C ++, the functions in the execution dll will be consistent with the normal call function.
This method can be used in BCB. A compilation error will occur in vs2005!