一个简单的DLL生成和测试
DLL文件内容:
SKLDll.h
#ifndef _SKLDLL_H_
#define _SKLDLL_H_
#ifndef DLL_API
#define DLL_API extern "C" __declspec(dllexport)
#else
#define DLL_API extern "C" __declspec(dllimport)
#endif
DLL_API int add(int a,int b);
#endif//_DLLMAIN_DLL_H_
SKLDll.cpp
#include "SKLDll.h"
#include<windows.h>
BOOL APIENTRY DllMain(
HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
MessageBox(NULL,"DLL_PROCESS_ATTACH", "Information", MB_OK | MB_ICONINFORMATION);
break;
case DLL_THREAD_ATTACH:
break;
case DLL_PROCESS_DETACH:
MessageBox(NULL, "DLL_PROCESS_DETACH", "Information", MB_OK | MB_ICONINFORMATION);
break;
case DLL_THREAD_DETACH:
break;
}
return TRUE;
}
int add(int a, int b)
{
return (a + b);
}
DLL显示(动态加载)调用代码:
#include<windows>
typedef int(*lpAddFun)(int, int);//宏定义函数指针类型 ,定义一个与add函数参数类型和返回类型相同的指针函数
int DllTest(){
HINSTANCE hDll;//dll句柄
lpAddFun addFun;//函数指针
hDll = LoadLibrary("SKLDll.dll");//通过win32的api函数 动态加载dll模块,并将dll模块句柄赋给了hdll;
if (hDll != NULL){
addFun = (lpAddFun)GetProcAddress(hDll, "add");//通过api函数将dll模块中函数add的地址赋给addfun
if (addFun != NULL){
int result = addFun(2, 3);
printf("%d\n", result);
}
FreeLibrary(hDll);
}
else
{
printf("%s", "DLL load failed");
}
return 0;
}
int main()
{
cout<<"come in main"<<endl;
DllTest();
}
运行结果:
先输出come in main 然后弹出DLL_PROCESS_ATTACH消息框,然后输出5,最后弹出DLL_PROCESS_DETACH消息框;