VC7.1环境下动态链接库的创建和调用

王朝vc·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

一、

动态链接库的创建示例

1. 选择VC.Net菜单项,选择文件->新建->项目,在弹出的新建项目的对话框中,选择项目类型为Visual C++ 项目,类别为MFC的工程,在右边的模板中,选择MFC DLL模板,给项目取名为TestDLL,选择好项目的位置,按确定健,进入应用程序设置。

2. 在应用程序设置中,我们可以看到,有三种DLL类型,它们依次对应着三类DLL。

选择“使用共享的MFC DLL”。

3. 点击完成,得到TestDLL工程。

4. 在TestDLL工程中新增MyDll类,如下:

/*MyDll.h*/

#pragma once

class AFX_CLASS_EXPORT CMyDll

{

public:

CMyDll(void);

~CMyDll(void);

int Max(int a, int b);

};

/*MyDll.cpp */

#include "StdAfx.h"

#include ".\mydll.h"

CMyDll::CMyDll(void)

{

}

CMyDll::~CMyDll(void)

{

}

int CMyDll::Max(int a, int b)

{

if( a>=b )

return a;

else

return b;

}

5. 在TestDLL工程中新增MyDllH.h,如下:

/*MyDllH.h*/

#pragma once

#pragma once

#include "MyDll.h"

#ifdef _AFXDLL

#ifdef _DEBUG

#define _MD_COMMENT "testdllD.lib"

#define _MD_MESSAGE "Automatically linking with testdllD.dll"

#else

#define _MD_COMMENT "Rtestdll.lib"

#define _MD_MESSAGE "Automatically linking with testdlll.dll"

#endif

#endif

#pragma comment(lib, _MD_COMMENT)

#pragma message(_MD_MESSAGE)

6. 设置TestDll工程的Property,如下:

General->OutPut Directory ..\..\Debug

Linker->General->OutPut File $(OutDir)/testdllD.dll

Linker->Advance->Import Library $(OutDir)/testdllD.lib

7. 修改TestDll.def,如下:

; testdll.def : Declares the module parameters for the DLL.

;LIBRARY "TestDll"

EXPORTS

; Explicit exports can go here

8. Build TestDll。得到TestDll.dll和TestDll.lib位于..\..\debug目录下。

二、

动态链接库的调用示例

1. 创建MFC Application 中的Dialog Based应用程序,得到TestDllApply工程。

2. 在TestDllApply工程中的stdafx.h中添加一项:

#include "MyDllH.h";

3. 添加对话框中“确定”按钮的消息响应函数,如下:

void CMyDllApllyDlg::OnBnClickedOk()

{

// TODO: Add your control notification handler code here

CMyDll myDll;

int i = myDll.Max(2,9);

OnOK();

}

4. 设置TestDllApply工程的Property,如下:

General->OutPut Directory ..\..\Debug

C++->General->Additional Include Directories TestDll工程中MyDll.cpp所在目录路径

Linker->General->Additional Library Directories TestDll工程中Debug文件夹的目录路径

Linker->Input->Additional Dependencies TestDll.lib

5. 编译、链接并运行TestDllApply工程,断点跟踪至int i = myDll.Max(2,9);语句,可以看到i的值是9。

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航