动态链接库

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 outputint x int y);
//若动态链接库中只导出类的成员函数,去掉class前的DLL_API,上面语句改为
// DLL_API  void  outputint 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);
如果DLLadd是这样定义的:int _stdcall add(int a, int b);那么typedef int (*ADDPROC)(int a, int b)应该为typedef int (_stdcall  *ADDPROC)(int a, int b);
动态加载动态链接库只需要dll文件就可以,不需要lib文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值