大家好,欢迎来到IT知识分享网。
通过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 0; } int csvMyAddReleaseInstance(void * ppHandle) { MyAdd* p = (MyAdd*)(ppHandle); if (p != NULL) { delete p; p = NULL; } return 0; } 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, 1, 3); csvMyAddReleaseInstance(pinst); cout << res << endl; system("pause"); return 0; }
源码:源码下载
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/29074.html