我们实现dll文件的显示调用,主要分为三个步骤:创建DLL、导出函数、使用DLL。其中离不开Windows API函数,使用到了LoadLibrary、GetProcAddress、 FreeLibrary等,以下是一个简单的示例程展示整个过程。:
1.创建DLL
MyLibrary.h
// MyLibrary.h
#ifndef MY_LIBRARY_H
#define MY_LIBRARY_H#ifdef MY_LIBRARY_EXPORTS
#define MY_LIBRARY_API __declspec(dllexport)
#else
#define MY_LIBRARY_API __declspec(dllimport)
#endifextern "C" {
MY_LIBRARY_API int add(int a, int b);
}#endif // MY_LIBRARY_H
MyLibrary.cpp
// MyLibrary.cpp
#include "MyLibrary.h"int add(int a, int b) {
return a + b;
}
2. 使用DLL的程序
// main.cpp
#include <windows.h>
#include <iostream>int main() {
HINSTANCE hinstLib = LoadLibrary(TEXT("MyLibrary.dll"));
if (!hinstLib) {
cerr << "Failed to load DLL: " << GetLastError() << endl;
return 1;
}using AddFunc = int(*)(int, int);
AddFunc add = (AddFunc)GetProcAddress(hinstLib, "add");
if (!add) {
cerr << "Failed to get function address: " << GetLastError() << endl;
FreeLibrary(hinstLib);
return 1;
}int result = add(4, 1);
cout << "4+ 1 = " << result << std::endl;FreeLibrary(hinstLib);
return 0;
}
注意:使用DLL的程序需要调用LoadLibrary加载DLL,GetProcAddress获取函数地址,使用完后通过FreeLibrary释放DLL。还有就是确保DLL的路径正确,无论是放在程序的同一目录下还是系统路径中,或者使用绝对路径加载。
标签:调用,int,LIBRARY,DLL,add,C++,MyLibrary,dll,MY From: https://blog.csdn.net/qq_57661075/article/details/139202097