DLL模块例2:使用__declspec(dllexport)导出函数,extern “C”规范修饰名称,隐式连接调用dll中函数

以下内容,我看了多篇文章,整合在一起,写的一个例子,关于dll工程的创建,请参考博客里另一篇文章:http://www.cnblogs.com/pingge/articles/3153571.html

有什么不对的欢迎指正!!!

1.头文件

1 //testdll.h
 2 #ifndef _TESTDLL_H_
 3 #define _TESTDLL_H_
 4 
 5 #ifdef TESTDLL_EXPORTS  
 6 #define TESTDLL_API __declspec(dllexport)   //这个修饰符使得函数能都被DLL输出,所以他能被其他应用函数调用
 7 #else  
 8 #define TESTDLL_API __declspec(dllimport)   //这个修饰符使得编译器优化DLL中的函数接口以便于被其他应用程序调用
 9 #endif
10 
11 #ifdef __cplusplus
12 extern "C"
13 {
14 #endif
15 
16 namespace MathFuncs  
17 {  
18     // This class is exported from the testdll.dll  
19     // Returns a + b  
20     extern TESTDLL_API double _stdcall Add(double a, double b);
21 
22     // Returns a - b  
23     extern TESTDLL_API double _stdcall Subtract(double a, double b);
24 
25     // Returns a * b  
26     extern TESTDLL_API double _stdcall Multiply(double a, double b);
27 
28     // Returns a / b  
29     // Throws const std::invalid_argument& if b is 0  
30     extern TESTDLL_API double _stdcall Divide(double a, double b);
31 }
32 
33 #ifdef __cplusplus
34 }
35 #endif
36 
37 #endif

使用__declspec(dllexport)导出DLL中的函数,extern “C”标志规范导出函数的修饰名称,是C++工程也能调用dll函数。

1 // testdll.cpp : 定义 DLL 应用程序的导出函数。
 2 
 3 #include "stdafx.h"
 4 #include "testdll.h"  
 5 #include <stdexcept>  
 6 using namespace std;  
 7 
 8 namespace MathFuncs  
 9 {  
10     double _stdcall Add(double a, double b)  
11     {  
12         return a + b;  
13     }  
14 
15     double _stdcall Subtract(double a, double b)  
16     {  
17         return a - b;  
18     }  
19 
20     double _stdcall Multiply(double a, double b)  
21     {  
22         return a * b;  
23     }  
24 
25     double _stdcall Divide(double a, double b)  
26     {  
27         if (b == 0)  
28         {  
29             throw invalid_argument("b cannot be zero!");  
30         }  
31         return a / b;  
32     }  
33 }

以上是导出函数的定义。

1 //demo.cpp
 2 #include <iostream>  
 3 #include "testdll.h"
 4 #pragma comment(lib,"testdll.lib")
 5 using namespace std;  
 6 
 7 int main()  
 8 {  
 9     double a = 7.4;  
10     int b = 99;  
11 
12     cout << "a + b = " <<  
13         MathFuncs::Add(a, b) << endl;  
14     cout << "a - b = " <<  
15         MathFuncs::Subtract(a, b) << endl;  
16     cout << "a * b = " <<  
17         MathFuncs::Multiply(a, b) << endl;  
18     cout << "a / b = " <<  
19         MathFuncs::Divide(a, b) << endl;  
20     return 0;  
21 }

这是一个测试的demo,隐式连接调用dll函数,一定要三件套.h .lib .dll

欢迎指正!!!
原文链接: https://www.cnblogs.com/pingge/p/3156998.html

欢迎关注

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

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

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

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

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

(0)
上一篇 2023年2月10日 上午2:14
下一篇 2023年2月10日 上午2:15

相关推荐