文件目录如下:
将项目dll_provider
的Configuration Type
设置为Dynamic Library (.dll)
文件内容如下:
IInterface.h
#ifndefIINTERFACE_H_#defineIINTERFACE_H_#include<windows.h>#defineXEXPORT__declspec(dllexport)extern"C"{
XEXPORTvoid __cdeclPrint(constchar*s);
XEXPORTint __cdeclIntegerAdd(constint a,constint b);}#endif
IInterface.cpp
#include"IInterface.h"#include<iostream>voidPrint(constchar*s){
std::cout<< s<< std::endl;}intIntegerAdd(constint a,constint b){return a+ b;}
example.cpp
#include<windows.h>#include<iostream>#include"../dll_provider/IInterface.h"typedefvoid(*pFunc1)(constchar*s);typedefint(*pFunc2)(constint a,constint b);intmain(){
HINSTANCE hDLL=LoadLibrary("dll_provider.dll");if(hDLL!=nullptr){
pFunc1 Print=(pFunc1)GetProcAddress(hDLL,"Print");if(Print!=nullptr){Print("Hello World");}else{
std::cerr<<"Print is nullptr"<< std::endl;}
pFunc2 IntegerAdd=(pFunc2)GetProcAddress(hDLL,"IntegerAdd");if(IntegerAdd!=nullptr){int a=1, b=2;
std::cout<<"a + b = "<<IntegerAdd(a, b)<< std::endl;}else{
std::cerr<<"Integer is nullptr"<< std::endl;}}else{
std::cerr<<"hDll is nullptr"<< std::endl;}return0;}