系列一中的例子,可以隐式调用,比较方便
静态链接库的调用及动态链接库的隐式调用
#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.
- 添加程序源代码
-
- #include "stdafx.h"
- #include <iostream>
- #include "../MathFuncsDll/MathFuncsDll.h"
- using namespace std;
- #pragma comment(lib,"..//Debug//MathFuncsDll.lib")
- int main()
- {
- double a = 7.4;
- int b = 99;
- cout<<"a + b = "<<MathFuncs::MyMathFuncs::Add(a,b)<<endl;
- cout<<"a - b = "<<MathFuncs::MyMathFuncs::Subtract(a,b)<<endl;
- cout<<"a * b = "<<MathFuncs::MyMathFuncs::Multiply(a,b)<<endl;
- cout<<"a / b = "<<MathFuncs::MyMathFuncs::Divide(a,b)<<endl;
- return 0;
- }
隐式调用:#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,获得函数指针,即可像使用本地函数一样使用导出函数。在此不再赘述。