c++调用动态dll库
首先把需要调用的动态库dll和它依赖的对象都要放入到运行目录,debug环境就是debug目录下了。
然后就写代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | #include <iostream> #include <windows.h> #include<string.h> //extern int OutPutQrCode(int version, int width, const char* outfile, unsigned char* data) typedef int (_cdecl *OutPutQrCode)( int , int , const char *, unsigned char *); typedef struct { int version; ///< version of the symbol int width; ///< width of the symbol unsigned char * data; ///< symbol data } QRcode; int main() { std::cout << "Hello World!\n" ; HMODULE hMod = LoadLibrary( "LLQrencode.dll" ); if (hMod != NULL) { /* 如果加载成功,则可通过GetProcAddress函数获取DLL中需要调用的函数的地址。 获取成功,sum指针不为空。 */ OutPutQrCode getCodeImg = (OutPutQrCode)GetProcAddress(hMod, "OutPutQrCode" ); GetProcAddress(hMod, "OutPutQrCode" ); if (getCodeImg != NULL) { getCodeImg(3, 130, "e:\\a.png" , (unsigned char *) "www.baidu.com" ); } FreeLibrary(hMod); /*在完成调用功能后,不在需要DLL支持,则可以通过FreeLibrary函数释放DLL。*/ } } |
构建一个方法指针:typedef int(_cdecl *OutPutQrCode)(int, int,const char*, unsigned char*);
要和需要使用的接口参数相同。
使用LoadLibrary加载库
寻找库里的接口并转换
OutPutQrCode getCodeImg = (OutPutQrCode)GetProcAddress(hMod, "OutPutQrCode");
调用:
getCodeImg(3, 130, "e:\\a.png", (unsigned char*)"www.baidu.com");
释放:
FreeLibrary(hMod);
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~