VC中创建DLL及调用+从DLL中导出C++类
1.创建一个空动态链接库工程:Win32 Dynamic-Link Library
2.添加Dll1.h,代码为:
#ifdef DLL1_API
#else
#define DLL1_API _declspec(dllimport)
#endif
DLL1_API int add(int a,int b);
class DLL1_API Point
{
public:
Point();
~Point();
void output(int x,int y);
protected:
private:
};
Point::Point()
{
}
Point::~Point()
{
}
添加Dll1.cpp,代码为:
#include <WINDOWS.H>
#include <STDIO.H>
#define DLL1_API _declspec(dllexport) //在程序编译时,头文件不参与编译,源文件单独编译
#include "Dll1.h"
int add(int a,int b)
{
return a + b;
}
void Point::output(int x,int y)
{
//返回调用者进程当前正在使用的那个窗口的句柄
HWND hwnd = GetForegroundWindow();
//获取DC
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));
//释放DC
ReleaseDC(hwnd,hdc);
}
编译后得到Dll1.dll,Dll1.lib
3.解决名字改编问题:
添加个Dll1.def文件,代码如下:
LIBRARY Dll1
EXPORTS
add
output
效果图:
4.隐式链接:调用Dll时,先将Dll1.hDll1.dll,Dll1.lib放入该工程的根目录下,如:D:\Program Files\Microsoft Visual Studio\MyProjects\DllTest
然后工程设置,添加Dll1.lib文件,如图:
添加头文件:#include "Dll1.h"
调用代码:
void CDllTestDlg::OnBtnAdd()
{
// TODO: Add your control notification handler code here
CString str;
str.Format("5 + 3 = %d",add(5,3));
MessageBox(str);
Point pt;
pt.output(5,3);
}
显示链接:
void CDllTestDlg::OnBtnAdd()
{
// TODO: Add your control notification handler code here
//
// Point pt;
// pt.output(5,3);
HINSTANCE hInst;
hInst = LoadLibrary("Dll1.dll");
typedef int (_stdcall *ADDRPROC) (int a,int b); //_stdcall标准调用约定
ADDRPROC Add = (ADDRPROC)GetProcAddress(hInst,MAKEINTRESOURCE(4));
if(!Add)
{
MessageBox("获取函数地址失败!");
return;
}
CString str;
str.Format("5 + 3 = %d",Add(5,3));
MessageBox(str);
}
如果采用动态加载方式使用dll时,在需要访问时,调用LoadLibary函数加载该dll;当不再需要访问该dll时,调用FreeLibrary函数释放对该dll的引用.