VC++6.0中编写DLL详细步骤及其使用
一、 编写DLL
1、 创建DLL
1.1、 FileNewProjectsWin32 Dynamic-Link Library; 在Project中输入名字MyDll,如下图:
1.2、 FileNewFilesC++ Source File, 在File中输入:MyDll.cpp如下图:
1.3、 FileNewFilesC/C++ Header File,在File中输入MyDll.h
1.4、 打开MyDll.h文件,输入一下内容:
#ifndef _MYDLL_H_
#define _MYDLL_H_
extern "C" _declspec (dllexport) int Max(int a, int b);
#endif
如下图:
1.5、 打开MyDll.cpp,输入一下内容:
#include "MyDll.h"
int Max(int a , int b)
{
if (a >= b)
{
return a ;
}
else
{
return b ;
}
}
如下图:
1.6、 在项目上右键, build ;结果如下:
二、 使用DLL
1、 FileNewProjectsWin32 Application, 在Project Name中输入UseMyDll,如下图:
2、 创建 UseMyDll.cpp 、UseMyDll.h ;如下:
3、 UseMyDll.h
#ifndef _USEMYDLL_H_
#define _USEMYDLL_H_
typedef int(*pMax) (int a, int b) ;//定义指向和dll中相同的函数原型指针
#endif
4、 UseMyDll.CPP
#include <stdio.h>
#include <iostream.h>
#include <windows.h>
#include "UseMyDll.h"
int main(void)
{
HINSTANCE hdll;
pMax max ;
hdll = LoadLibrary("../../MyDll/Debug/MyDll.dll") ;
if (hdll == NULL){
printf("can not find dll file.") ;
return 1 ;
}
max =(pMax)GetProcAddress(hdll, "Max") ;
if (max == NULL)
{
printf("can not find the Max function.");
return 1 ;
}
int ret = max(1, 1255) ;
printf("比较结果:%d\n", ret) ;
FreeLibrary(hdll) ;
return 0 ;
}
5、 编译,运行UseMyDll ,ok。
Linking...
LIBCD.lib(wincrt0.obj) : error LNK2001: unresolved external symbol _WinMain@16
Debug/UseMyDll.exe : fatal error LNK1120: 1 unresolved externals
Error executing link.exe.
解决:
ProjectSettingLinkProject Options中修改:
subsystem: windows subsystem: console;