1.新建一个项目生成dll
首先我们新建一个项目生成一个Dynamic Library(动态链接库) dll
里面非常简单,只有一个add方法。等下我们就要在其他项目里尝试载入这个dll,调用里面的这个add方法。
// MyDLL.cpp : Defines the entry point for the DLL application.
//
#include "stdafx.h"
extern "C"
{
_declspec(dllexport) int add(int x, int y);
}
int add(int x, int y){
return x + y;
}
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
}
如果开始项目不是没有生成dll,记得打开项目的属性,选择Dynamic Library。
2.新建一个项目载入dll
// DLLTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <windows.h> //must include this
typedef int (*MyAdd)(int x, int y);
int main(int argc, char* argv[])
{
HMODULE hmod = NULL;
hmod = ::LoadLibrary("MyDLL.dll"); //load dll
if(hmod == NULL){
printf("load MyDLL.dll failed!");
return 0;
}
MyAdd Add = (MyAdd)GetProcAddress(hmod, "add");
if(!Add){
printf("get function failed!");
return 0;
}
printf("test add(): 1+2=%d\n", Add(1,2));
::FreeLibrary(hmod); // release resource
getchar();
return 0;
}
效果图:
成功调用!
项目下载地址:c++动态载入dll