一、制作DLL文件的步骤
2. 新建一个空项目(Empty project)
在类视图里新建一个普通类(Generic)
这是头文件
#ifndef MYDLL_H
#define MYDLL_H
#define MYDLLAPI extern "C" _declspec(dllexport)
MYDLLAPI int add(int a,int b);
#endif
这是源文件
// MYDLL.cpp: implementation of the CMYDLL class.
//
//
#include "MYDLL.h"
int add(int a,int b)
{
return a+b;
}
编译后会生成一个DLL文件,这个文件可以供其它程序调用
二、DLL文件的调用
#include <stdio.h>
#include <windows.h>
//
// Construction/Destruction
//
typedef int(*lpAddFun)(int,int); //自定义函数指针类型
int add(int a,int b)
{
int result;
HINSTANCE hDll; //DLL句柄
lpAddFun addFun;
hDll = LoadLibrary("..\\SimpleDll.dll");
if(hDll != NULL)
{
addFun = (lpAddFun)GetProcAddress(hDll,"add");
if(addFun != NULL)
{
result = addFun(a,b);
}
FreeLibrary(hDll);
}
return result;
}
int main(int argc,char args[])
{
printf("The result is %d\n",add(1,2));
return 0;
}
运行结果: