1 DLL.cpp文件:
_declspec(dllexport) int add(int a, int b)
{ return a+b; }
在其他工程中用add的时候要写上下面这句话:
_declspec(dllimport) int add(int a, int b);也可以是:extern int add(int a, int b);
2 DLL.h文件:
#ifdef DLL_API
#else
#defune DLL_API _declspec(dllimport)
#endif
DLL_API int add(int a, int b);
DLL.cpp文件:
#define DLL_API _declspec(dllexport)
#include"DLL.h"
int add(int a, int b)
{ return a+b; }
3动态链接库中导出类
DLL.h文件:
#ifdef DLL_API
#else
#defune DLL_API _declspec(dllimport)
#endif
class DLL_API Point
{ public:
void output(int x, int y);
//若动态链接库中只导出类的成员函数,去掉class前的DLL_API,上面语句改为
// DLL_API void output(int x, int y);此时必须是pulic型};
DLL.cpp文件:
#define DLL_API _declspec(dllexport)
#include"DLL.h"
#include"windows.h" //使用了windows API函数
#include"stdio.h" //C标准输入输出头文件
void Point::output(int x, int y)
{ HWND hwnd = GetForegroundWindow(); // GetForegroundWindow得到当前使用窗口句柄
HDC hdc = GetDC(hwnd);
Char buf[20];
memset(buf, 0,20);
sprintf(buf, "x=%d, y=%d", x, y);
TextOut(hdc,0 , 0, buf, strlen(buf));
ReleaseDC(hwnd, hdc); }
4 防止C++和C语言相互调用名字改变
DLL.h文件:
#ifdef DLL_API
#else
#defune DLL_API extern "C" _declspec(dllimport) //C是大写的
#endif
DLL_API int add(int a, int b);
DLL.cpp文件:
#define DLL_API extern "C" _declspec(dllexport)
#include"DLL.h"
int add(int a, int b)
{ return a+b; }
extern "C" 的缺点是不能导出类的成员函数,只能到处全局函数。而且导出函数调用约定改变了名字还是会改变。
DLL_API int add(int a, int b); 是C调用约定
DLL_API _stdcall int add(int a, int b); 是标准调用约定
所以可以用模块定义文件来解决名字改变问题:
DLL.h文件:
#ifdef DLL_API
#else
#defune DLL_API _declspec(dllimport)
#endif
DLL_API int add(int a, int b);
DLL.cpp文件:
#define DLL_API _declspec(dllexport)
#include"DLL.h"
int add(int a, int b)
{ return a+b; }
在工程目录下新建文本文件,重命名为DLL.def,再添加到工程中。内容为:
LIBRARY DLL
EXPORTS
add
5 动态加载动态链接库的导出函数
在用到动态链接库函数的地方写如下的代码来加载dll:
HINSTANCE hInst;
hInst = LoadLibrary("DLL.dll");
typedef int (*ADDPROC)(int a, int b);
// GetProcAddress得到指定导出动态链接库的函数地址,返回值是函数地址
ADDPROC Add = (ADDPROC)GetProcAddress(hInst, "add");
//也可以通过序号来访问动态链接库函数,MAKEINTRESOURCE将序号转化为字符串
//ADDPROC Add = (ADDPROC)GetProcAddress(hInst, MAKEINTRESOURCE(1));
Add (5, 3);
FreeLibrary(hInst);
如果DLL中add是这样定义的:int _stdcall add(int a, int b);那么typedef int (*ADDPROC)(int a, int b)应该为typedef int (_stdcall *ADDPROC)(int a, int b);
动态加载动态链接库只需要dll文件就可以,不需要lib文件
动态链接库
最新推荐文章于 2024-10-14 11:33:39 发布