C++ dll实例

动态链接库的制作:

Windows桌面向导-应用程序类型:动态链接库(.dll) 空项目 MyDynamicLib

头文件声明函数时,在前面加上 extern "C" __declspec(dllexport)

1 //MyDynamicLib.h
2 #pragma once
3 extern "C" __declspec(dllexport) int GetMaxCommDiv(int a, int b);
4 extern "C" __declspec(dllexport) int GetMinCommMul(int a, int b);

 

 1 //MyDynamicLib.cpp
 2 #include "MyDynamicLib.h"
 3 
 4 int GetMaxCommDiv(int a, int b)
 5 {
 6     int x = 1;
 7     int ires;
 8     if (a < b)
 9         return 0;
10     if (b == 0)
11         return 0;
12     while (x != 0)
13     {
14         x = a % b;
15         a = b;
16         ires = b;
17         b = x;
18     }
19     return ires;
20 }
21 
22 int GetMinCommMul(int a, int b)
23 {
24     int x = 1;
25     int ires;
26     int m, n;
27     m = a; n = b;
28     if (a < b)
29         return 0;
30     if (a == 0)
31         return 0;
32     if (b == 0)
33         return 0;
34     while (x != 0)
35     {
36         x = a % b;
37         a = b;
38         ires = b;
39         b = x;
40     }
41     ires = (m * n) / ires;
42     return ires;
43 }

 

DLL文件的使用:

将.h .dll .lib三个文件都复制到工程目录,不需要添加到工程里,就可以直接使用.

 1 #include <iostream>
 2 #include "MyDynamicLib.h"
 3 #pragma comment(lib, "MyDynamicLib")
 4 
 5 int main()
 6 {
 7     int m = 360, n = 100;
 8     std::cout << "MaxCommDiv: " << GetMaxCommDiv(m, n) << std::endl;
 9     std::cout << "MinCommMul: " << GetMinCommMul(m, n) << std::endl;
10     return 0;
11 }

 动态加载动态链接库:

将.h .dll .lib三个文件都复制到工程目录,不需要添加到工程里,就可以直接使用.

 1 #include <iostream>
 2 #include <windows.h>
 3 #include "MyDynamicLib.h"
 4 
 5 
 6 int main()
 7 {
 8     int m = 360, n = 100;
 9     typedef int(__cdecl* MyFunc)(int, int);
10     HMODULE hModule = ::LoadLibrary("MyDynamicLib.dll");
11     if (hModule == NULL)
12         return 0;
13     MyFunc GetValue = (MyFunc)GetProcAddress(hModule, "GetMaxCommDiv");
14 
15     std::cout << "MaxCommDiv: " << GetValue(m, n) << std::endl;
16 
17     GetValue = (MyFunc)GetProcAddress(hModule, "GetMinCommMul");
18     std::cout << "MinCommMul: " << GetValue(m, n) << std::endl;
19 
20     FreeLibrary(hModule);
21     return 0;
22 }

 

posted @ 2023-02-14 10:50  kaling  阅读(54)  评论(0编辑  收藏  举报