WEB页面通过ActiveX控件调用DLL动态库(二):VS2013编写C++调用DLL
C++调用DLL有两种方法:
1、静态调用:需要包含调用DLL的dll文件、lib文件、h文件
2、动态调用:采用windows专用库函数直接在程序中包含所调用DLL路径即可加载。
(一)动态调用
采用动态调用需要知道所调用DLL中的需要的函数形式即返回值,入参等。
1.VS2013创建一个C++空项目
2.右键添加一个cpp源文件,testDLL_dynamic.cpp
3在testDLL_dynamic.cpp中输入一下代码:
#include <iostream>
#include <windows.h>
using namespace std;
typedef int(*AddFunc)(int, int); //定义指针函数、接口。
typedef void(*FunctionFunc)();
int main()
{
AddFunc _AddFunc;
FunctionFunc _FunctionFunc;
cout << "---获取DLL---." << endl;
// L 表示使用UNICODE 字符集,要和项目的字符集保持一致。
HINSTANCE hInstLibrary = LoadLibrary("C:\\Users\\dell\\Desktop\\testDLL\\testDLL\\Release\\testDLL.dll");//调用DLL的目录路径
if (hInstLibrary == NULL)
{
cout << "Dll 加载【失败】." << endl;
FreeLibrary(hInstLibrary);
}
else{
cout << "Dll 加载【成功】." << endl;
}
_AddFunc = (AddFunc)GetProcAddress(hInstLibrary, "Add");
_FunctionFunc = (FunctionFunc)GetProcAddress(hInstLibrary, "Function");
if ((_AddFunc == NULL) || (_FunctionFunc == NULL))
{
FreeLibrary(hInstLibrary);//释放
}
else{
cout << "---获取DLL函数【OK】---." << endl;
}
cout << _AddFunc(1, 3) << endl; // 开始调用
_FunctionFunc(); //
cin.get(); // 获得焦点,这样就不会程序就不会一闪而过了。
FreeLibrary(hInstLibrary);//调用完后,要释放内存。
return(1);
}
4.编译运行,结果如下:
(二)静态调用
1.VS2013创建一个C++空项目,同上
2.右键添加一个cpp源文件,testDLL_static.cpp
3.将教程(一)中在文件夹Release生成的testDLL.dll与testDLL.lib,与testDLL.h文件复制到testDLL_static工程目录下。
4.在testDLL_static.cpp中输入一下代码:(只需要将testDLL.h文件加入即可),在此只验证了一个函数加发Add函数。
#include <iostream>
#include "testDLL.h"
using namespace std;
int main()
{
int sum = Add(8, 11);
cout << "return value: " << sum << endl;
}
5.在解决方案右键选择属性,选择C/C++,常规,附加包含目录。添加目录,此目录为有testDLL.dll与testDLL.lib,与testDLL.h文件的目录。
选择链接器,常规,逐用户重定向选择是,附加库目录与上面一样的目录。
选择链接器,输入,附加依赖项。填写testDLL.lib
6.右键生成,运行成功,结果如下: