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 }

 

原文链接: https://www.cnblogs.com/kaling/p/17118896.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++ dll实例

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/317960

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月16日 下午2:55
下一篇 2023年2月16日 下午2:56

相关推荐