您的位置:首页 > 其它

DLL小结

2011-09-05 12:15 246 查看
创建DLL

vs新建项目,选择智能设备win32项目,然后下一步,选择dll。然后里面会自动生成一个dll的入口函数

然后cpp里面实现自己的函数

在。def文件里面导出自己的函数

如:

第一步,在def文件中添加导出函数,xxx即是注册表里指定的前缀:

EXPORTS
; Explicit exports can go here
xxx_Close

第二步,实现函数,xxx即是注册表里指定的前缀:

/***************************************************************************
*
* Function Name: DllMain
* Purpose: service entrance
* Input:
hinstDLL: Handle to the DLL.
dwReason: Specifies a flag indicating why the DLL entry-point function is being called.
lpvReserved: Specifies further aspects of DLL initialization and cleanup.
* Output:none
* Return:TRUE
***************************************************************************/
BOOL APIENTRY DllMain( HANDLE hinstDLL, DWORD  dwReason,  LPVOID lpvReserved)
{
switch( dwReason )
{
case DLL_PROCESS_ATTACH:
g_hInst=(HINSTANCE)hinstDLL;
break;
case DLL_PROCESS_DETACH:
{
//..
break;
}
}
return TRUE;
}
/***************************************************************************
*
* Function Name:xxx_Close
* Purpose: This function is implemented by a service and will be called by Services.exe.
* Input:
dwData:Specifies the value returned by xxx_Open (Services.exe) for the given service instance.
* Output:none
* Return:TRUE indicates success. FALSE indicates failure. * Remarks:This function is called when a service instance is closing during an application's call to CloseHandle.
***************************************************************************/
BOOL xxx_Close(DWORD dwData)
{
//..
//return FALSE;
}


或者在建工程的时候最后一步选择导出实例,这样,就不用def文件,但是要加上一个extern "C" __declspec(dllexport)

其实我们可以看到在。h文件中已经有了一个宏定义帮我们设置好了,我们只需要按照实例做就行

其实这就是dll的两种方式

调用DLL有两种方法:静态调用和动态调用.

(一).静态调用其步骤如下:

1.把你的youApp.DLL拷到你目标工程(需调用youApp.DLL的工程)的Debug目录下;

2.把你的youApp.lib拷到你目标工程(需调用youApp.DLL的工程)目录下;

3.把你的youApp.h(包含输出函数的定义)拷到你目标工程(需调用youApp.DLL的工程)目

录下;

4.打开你的目标工程选中工程,选择Visual C++的Project主菜单的Settings菜单;

5.执行第4步后,VC将会弹出一个对话框,在对话框的多页显示控件中选择Link页。然

后在Object/library modules输入框中输入:youApp.lib

6.选择你的目标工程Head Files加入:youApp.h文件;

7.最后在你目标工程(*.cpp,需要调用DLL中的函数)中包含你的:#include "youApp.h"

注:youApp是你DLL的工程名。

2.动态调用其程序如下:

动态调用时只需做静态调用步骤1.

{

HINSTANCE hDllInst = LoadLibrary("youApp.DLL");

if(hDllInst)

{

typedef DWORD (WINAPI *MYFUNC)(DWORD,DWORD);

MYFUNC youFuntionNameAlias = NULL; // youFuntionNameAlias 函数别名

youFuntionNameAlias = (MYFUNC)GetProcAddress

(hDllInst,"youFuntionName");

// youFuntionName 在DLL中声明的函数名

if(youFuntionNameAlias)

{

youFuntionNameAlias(param1,param2);

}

FreeLibrary(hDllInst);

}

}

显式(静态)调用:

LIB + DLL + .H,注意.H中dllexport改为dllimport
隐式(动态)调用:

DLL + 函数原型声明,先LoadLibrary,再GetProcAddress(即找到DLL中函数的地址),不用后FreeLibrary
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: