关于动态链接库DLL的入门学习之二

系列一中的例子,可以隐式调用,比较方便

静态链接库的调用及动态链接库的隐式调用

#include "xxx.h"     //包含链接库的头文件

#pragma comment(lib, "xxx")  //隐式调用库文件.lib

上述代码就是隐式链接的方法。其中语句#pragma comment(lib,"xxx")可以通过工程设置对话框来设置代替。

  • properties->Configuration Properties->Debugging,在Enviroment中设置动态库.dll文件的路径名。其格式为:PATH=<.dll文件名>。
  • Configuration Properties->C/C++->General,在Additional Include Directories中添加snmp++类库头文件的路径,多个路径之间用分号隔开。
  • Configuration Properties->C/C++->Code Generation,在Runtime Library中指定运行时库为Muti-thread Debug Dll (/MDd)
  • Configuration Properties->Linker->General->Additional Library Directories中指定.lib库文件的所在目录,在Configuration Properties->Linker->Input中输入xxx.lib.
  • 添加程序源代码
    1. #include "stdafx.h"  
    2. #include <iostream>  
    3. #include "../MathFuncsDll/MathFuncsDll.h"  
    4. using namespace std;  
    5. #pragma comment(lib,"..//Debug//MathFuncsDll.lib")  
    6. int main()  
    7. {  
    8.     double a = 7.4;  
    9.     int b = 99;  
    10.   
    11.     cout<<"a + b = "<<MathFuncs::MyMathFuncs::Add(a,b)<<endl;  
    12.     cout<<"a - b = "<<MathFuncs::MyMathFuncs::Subtract(a,b)<<endl;  
    13.     cout<<"a * b = "<<MathFuncs::MyMathFuncs::Multiply(a,b)<<endl;  
    14.     cout<<"a / b = "<<MathFuncs::MyMathFuncs::Divide(a,b)<<endl;  
    15.   
    16.     return 0;  
    17. }  

    隐式调用:#include "stdafx.h" #include <iostream> #include "../Debug/MathFuncsDll.h" using namespace std; using namespace MathFuncs;#pragma comment(lib,"../Debug/MathFuncsDll.lib")

  • Build->Build Solution,在输出目录中即可生成可执行文件xxx.exe文件。

至此,运行xxx.exe文件即可看到程序的运行结果。对上述源代码进行分析可以看出,在该动态库中导出的是函数而不是类。对于函数的导出,也可以用显式调用方式。

3)动态链接库的显式调用

显式调用的动态加载主要是通过LoadLibrary和GetProcAddress两个函数来实现的。

  • LoadLibrary()用于装载模块,动态链接库和可执行程序都是模块,如果函数执行成功,返回模块句柄,这个句柄会在GetProcAddress中使用。其语法格式如下:

      HINSTANCE LoadLibrary(LPCTSTR lpLibFileName);

      其中:lpLibFileName是要装载的动态链接库和可执行程序的文件名,可以是相对路径也可以是绝对路径。

  • GetProcAddress()用于获得模块的函数地址。如果函数执行成功,返回模块中具体函数的指针。其语法为:

      GetProcAddress(HMODULE hModule, LPCSTR lpProcName)

      其中:hModule是加载到内存中的模块的句柄,主要指LoadLibrary的返回值。

            lpPorcName是函数的名称

  在显式调用中,首先要定义一个指向导出函数的函数指针,然后调用LoadLibrary和GetProcAddress,获得函数指针,即可像使用本地函数一样使用导出函数。在此不再赘述。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值