Dll的创建与使用

 一. 创建Dll

1. 使用__declspec(dllexport)导出函数或类。

    Note:确认LOGUTILCPP_API已经定义。Property Pages->Configuration Properties->C/C++->Preprocessor->Preprocessor Definitions.

#ifdef LOGUTILCPP_EXPORTS

#define LOGUTILCPP_API extern "C" __declspec(dllexport)

#else

#define LOGUTILCPP_API extern "C" __declspec(dllimport)

#endif

 

// This function is exported from the LogUtilCPP.dll

LOGUTILCPP_API void PrintLog();

 

// This class is exported from the LogUtilCPP.dll

class LOGUTILCPP_API CLogUtilCPP {

public:    

        static CLogUtilCPP* GetInstance();

        void LogBegin(wstring LogfileName);

        void LogError(wstring strFormat,...);

        void LogInfo(wstring strFormat,...);

        void LogWarning(wstring strFormat,...);

        void LogEnd();

}

 

2. 使用def文件导出函数。

    创建一个普通的.h文件和.CPP文件,.h文件如下:

#include <windows.h>

// TODO: add your methods here.

void LogBegin(LPCWSTR LogfileName);

void LogError(LPCWSTR strFormat,...);

void LogInfo(LPCWSTR strFormat,...);

void LogWarning(LPCWSTR strFormat,...);

void LogEnd();

 

   def文件格式如下:

LIBRARY "LogUtilCPP"

DESCRIPTION "LogUtilCPP.Dll [Get .bmp picture if it is failed]"

EXPORTS

LogBegin        @1

LogError          @2

LogInfo           @3

LogWarning   @4

LogEnd            @5

 

3. 使用def文件导出类

    参照上一篇文章,"用DEF文件从Dll中导出C++类"。http://blog.csdn.net/nathannemo/archive/2008/12/15/3521205.aspx

 

4. 关于DllMain函数

   使用VS向导创建一个Dll工程会自动产生一个DllMain函数,如果你没有更新(即没有使用)这个DllMain函数,可以将它删除掉。

   当Windows加载DLL模块时调用这一函数。系统首先调用全局对象的构造函数,然后调用全局函数DLLMain。如果程序员没有为DLL模块编写一个DLLMain函数,系统会从其它运行库中引入一个不做任何操作的缺省DLLMain函数版本。在单个线程启动和终止时,DLLMain函数也被调用。

 

二. Dll的使用

方法一步骤:

1. Reference Dll工程。

2. 包含Dll的头文件。

3. 像普通的成员函数一样使用。

 

方法二步骤:

1.将Dll的头文件,.lib文件,.dll文件拷到当前工程文件夹中。

2.包含Dll的头文件。

3.Property Pages->Configuration Properties->Linker->Input->Additional Dependencies 添加.lib文件。

4.像普通函数一样使用。

 

方法三步骤:

1.将.Dll文件拷到当前工程文件夹中。

2.使用动态调用的方式使用,实例如下:

typedef void (* PrintfLogWarning)(LPCWSTR,...);

HINSTANCE hinstLib = LoadLibrary(L"LogUtillCPP.Dll");

if(hinstLib)

{

      PrintfLogWarning pLogWarning = (PrintfLogWarning)GetProcAddress (hinstLib,"LogWarning");

      pLogWarning(L"Log Warning.");

}

FreeLibrary(hinstLib);

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值