是大臣阿诺德爵士:使用 VC6.0 调用.生成 DLL
来源:百度文库 编辑:中财网 时间:2024/05/11 03:55:59
1.使用 VC6.0 生成 DLL
新建项目 “Win32 Dynamic-Link Library”,输入项目名称,确定后选择 “A simple DLL project” 点击“完成”。
以下为cpp文件自动生成的代码:
#include "stdafx.h"
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
}
编辑cpp文件:
在#include "stdafx.h"的下一行加入
extern "C" __declspec(dllexport) int fun(int a, int b);
/*
这是C格式导出函数;
这种写法一般用在C++写的DLL中,指按C的规则导出这个函数,否则导出的函数会很怪;
加上 extern "C" 表示按标准C格式导出函数.如果去掉仅兼容C++;
其中 int fun(int a, int b) 这部分代码是我们想用 dll 实现的函数原型声明
如果还想加入其他的可以继续加入 extern "C" __declspec(dllexport) int fun1(int a, int b);
*/
DllMain 是 DLL 的默认入口函数,类似于C语言的main函数,该例子无需修改此处,在 DllMain 的后面加入:
int fun(int a,int b)
{
return a+b;
}
这就是我们想用 DLL 实现的函数的定义,build 之后就会在 debug 目录下生成我们想要的 dll 文件
2.调用 DLL
新建一个 Win32 Console Application 工程,把刚才生成的 dll 文件拷贝到工程的根目录下
在 stdafx.h 文件中加入:#include
编辑cpp文件:
#include "stdafx.h"
typedef int (*PFUN)(int,int);
void main()
{
HMODULE hModule = ::LoadLibrary("dlltest.dll");
PFUN newfun = (PFUN)::GetProcAddress(hModule,"fun");
int i = newfun(1,2);
printf("The result is %d\n",i);
::FreeLibrary(hModule);
}
然后,运行就可以看到结果了