win32环境C语言实现最基本的DLL编写及调用实例,测试通过

开发环境是DEV C++,采用C语言编写
创建一个DLL项目,项目名称hello,DLL编写采用的是DEV C++中的示例代码

头文件dll.h
#ifndef _DLL_H_
#define _DLL_H_

#if BUILDING_DLL
# define DLLIMPORT __declspec (dllexport)
#else /* Not BUILDING_DLL */
# define DLLIMPORT __declspec (dllimport)
#endif /* Not BUILDING_DLL */


DLLIMPORT void HelloWorld (void);


#endif /* _DLL_H_ */

C文件
dllmain.c
#include <stdio.h>
#include <stdlib.h>

DLLIMPORT void HelloWorld ()
{
MessageBox (0, "Hello World from DLL!\n", "Hi", MB_ICONINFORMATION);
}


BOOL APIENTRY DllMain (HINSTANCE hInst /* Library instance handle. */ ,
DWORD reason /* Reason this function is being called. */ ,
LPVOID reserved /* Not used. */ )
{
switch (reason)
{
case DLL_PROCESS_ATTACH:
break;

case DLL_PROCESS_DETACH:
break;

case DLL_THREAD_ATTACH:
break;

case DLL_THREAD_DETACH:
break;
}

/* Returns TRUE on success, FALSE on failure */
return TRUE;
}

还有要注意的在.def文件中指定输出的函数,编译生成了hello.dll文件

DLL调用部分
dllcall.c
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>

HINSTANCE hDLL; //定义DLL包柄
typedef void ( *func)(); //定义函数指针原型
func hello; //定义函数指针
int main()
{
if (hDLL == NULL)
hDLL=LoadLibrary("hello.dll"); //加载DLL
hello = (func)GetProcAddress(hDLL,"HelloWorld"); //获取函数指针
hello();
FreeLibrary(hDLL); //释放DLL
return 0;
}


文章来自: 本站原创
Tags:
评论: 0 | 查看次数: 11252