动态链接库编程
动态链接库编程.打开VC工程,选择文件-新建-在工程选项卡选择Win32 Dynamic-Link library,工程名lin单击确定,选择一个空的DLL工程,单击确定,选择文件-新建-在文件选项卡选择C++Source File,输入文件名lin单击确定,输入原文件如下代码
int add(int a,int b)
{ return a+b;}
int jian(int a,int b)
{ return a-b;}
在工程lin目录下新建一个模块定义文本文件lin.def,单击工程-选择添加到-文件,将lin.def添加到工程
在模块定义文件lin.def中输入如下代码
LIBRARY LIN //表明LIN属于动态链接库
EXPORTS //动态链接库导出函数名
add
jian
编译后在工程lin\Debug目录下生成lin.dll动态链接库文件,
再新建一个对话框工程,工程名test,为对话框添加2个按钮控件,并为2个按钮控件添加2个消息响应函数,消息响应函数中输入如下代码
void CTestDlg::OnButton1()
{
HINSTANCE hin=LoadLibrary("lin.dll");//加载动态链接库文件
if(hin!=NULL)
MessageBox("process false");
typedef int (*ADDFUNC)(int a,int b);//定义一个指向函数的指针变量
ADDFUNC f1=(ADDFUNC)GetProcAddress(hin,"add");//获得动态链接库中函数的地址
if(!f1)
{MessageBox("false");
return;}
CString s;
s.Format("a+b=%d",f1(5,9));//通过函数指针调用动态链接库中函数
MessageBox(s);
// TODO: Add your control notification handler code here
}
void CTestDlg::OnButton2()
{
HINSTANCE hinstance=LoadLibrary("lin.dll");//加载动态链接库文件
typedef int (*fn)(int a,int b);//定义一个指向函数的指针变量
fn f1=(fn)GetProcAddress(hinstance,"jian");//获得动态链接库中函数的地址
if(!f1)
{MessageBox("false");
return;}
CString s;
s.Format("a+b=%d",f1(5,9));//通过函数指针调用动态链接库中函数
MessageBox(s);
// TODO: Add your control notification handler code here
}