一、生成DLL
win32控制台程序,按图选择选项
新建 cpp 文件 :
#include "iostream"
#include "CreateDLL.h"
using namespace std;
int Add(int &a,int&b)
{
return a+b;
}
CreateDLL.h
#pragma once
extern "C" __declspec(dllexport) int Add(int&a,int&b);
使用dll 文件:
大致分两种,静态链接和动态链接
1、在c++目录 包含 dll 和lib路径
#include "iostream"
#include "TestDLL.h"
using namespace std;
#pragma comment(lib,"..\\Debug\\DLL1.lib")
void main()
{
int a=2,b=3;
cout<<Add(a,b)<<endl;
getchar();
}
即可
2、运行期动态加载
要用到三个windowsAPI 函数 LoadLibrary,GetProcAddress,FreeLibrary;
#include "iostream"
#include "windows.h"
using namespace std;
typedef int (*f)(int&,int&);
void main()
{
f f1=NULL;
HMODULE h=
::LoadLibrary(TEXT("E:\\C++\\TestDLL\\Debug\\DLL1.dll"));
if (h==NULL)
{
::FreeLibrary(h);
}
else
{
f1=(f)::GetProcAddress(h,"Add");
if (f1==NULL)
{
::FreeLibrary(h);
}
}
int a=2,b=3;
cout<<f1(a,b)<<endl;
::FreeLibrary(h);
getchar();
}