通过LoadLibraryA 和 GetProcAddress,动态调用无需配置链接库lib和相关的头文件配置。下面介绍一个例子的实现
1、动态库
A、加法类
头文件:
#pragma once
class MyAdd
{
public:
MyAdd();
virtual ~MyAdd();
int add(int a, int b);
float add(float a, float b);
};
源文件:
#include "MyAdd.h"
MyAdd::MyAdd()
{
}
MyAdd::~MyAdd()
{
}
int MyAdd::add(int a, int b)
{
return a + b;
}
float MyAdd::add(float a, float b)
{
return a + b;
}
B、导出加法类接口
头文件:
#include <stdlib.h> #include "MyAdd.h"
#include "add_api.h" int csvMyAddGetInstance(void ** ppHandle)
{
MyAdd* p = new MyAdd();
*ppHandle = p;
return ;
} int csvMyAddReleaseInstance(void * ppHandle)
{
MyAdd* p = (MyAdd*)(ppHandle);
if (p != NULL)
{
delete p;
p = NULL;
}
return ;
} int csvMyAddaddInt(void ** ppHandle, int a, int b)
{
MyAdd* p = (MyAdd*)(ppHandle);
if (p == NULL) return INT_MIN; return a + b;
} float csvMyAddaddFloat(void ** ppHandle, float a, float b)
{
MyAdd* p = (MyAdd*)(ppHandle);
if (p == NULL) return INT_MIN; return a + b;
} 源文件:
#ifndef CSV_ADD_API_H
#define CSV_ADD_API_H
#ifdef CSVADDAPI_LIB
#define CSVADDAPI_LIB_EXPORT extern "C" __declspec(dllexport)
#else
#define CSVADDAPI_LIB_EXPORT extern "C" __declspec(dllimport)
#endif
CSVADDAPI_LIB_EXPORT int csvMyAddGetInstance(void ** ppHandle);
CSVADDAPI_LIB_EXPORT int csvMyAddReleaseInstance(void * ppHandle);
CSVADDAPI_LIB_EXPORT int csvMyAddaddInt(void ** ppHandle, int a, int b);
CSVADDAPI_LIB_EXPORT float csvMyAddaddFloat(void ** ppHandle, float a, float b);
#endif //CSV_ADD_API_H
2、调用动态库
#include <iostream>
#include <stdlib.h>
#include <string>
#include<stdio.h>
#include <windows.h>
using namespace std; /*通过LoadLibraryA 和 GetProcAddress,动态调用无需配置链接库lib和相关的头文件*/ typedef int(*MyAddGetInstance)(void **ppHandle); //定义类型:获取加法类的函数指针
typedef int(*MyAddReleaseInstance)(void *ppHandle); //定义类型:声明释放加法类的函数指针
typedef int(*MyAddAddInt)(void **ppHandle, int a, int b); //定义类型:声明整数的加法函数指针 int main(int argc, char** argv)
{
/*导入DLL库*/
string dll_path = "MyDll.dll";
HINSTANCE phandle = LoadLibraryA(dll_path.c_str()); /*获取 DLL库内部的函数句柄*/
MyAddGetInstance csvMyAddGetInstance;
csvMyAddGetInstance = (MyAddGetInstance)GetProcAddress(phandle, "csvMyAddGetInstance");
MyAddReleaseInstance csvMyAddReleaseInstance;
csvMyAddReleaseInstance = (MyAddReleaseInstance)GetProcAddress(phandle, "csvMyAddReleaseInstance");
MyAddAddInt myAddAddInt;
myAddAddInt = (MyAddAddInt)GetProcAddress(phandle, "csvMyAddaddInt"); /*调用函数*/
void* pinst = NULL;
csvMyAddGetInstance(&pinst);
int res = myAddAddInt(&pinst, , );
csvMyAddReleaseInstance(pinst); cout << res << endl; system("pause");
return ;
}
源码:源码下载