我经常在Windows上看到__declspec(dllexport) / __declspec(dllimport)指令,在Linux上看到带有函数的__attribute__((visibility("default"))),但我不知道为什么。你能向我解释一下,为什么我需要对共享库使用这些指令?
发布于 2022-04-22 16:43:45
当您需要从Dll调用函数时(通过导出它),可以从应用程序访问该函数时,将使用__declspec(dllexport)。
示例这是一个名为"fun.dll“的dll:
// Dll.h :
#include <windows.h>
extern "C" {
__declspec(dllexport) int fun(int a); // Function "fun" is the function that will be exported
}
// Dll.cpp :
#include "Dll.h"
int fun(int a){
return a + 1;
}您现在可以从任何应用程序中访问"fun.dll“中的”乐趣“:
#include <windows.h>
typedef int (fun)(int a); // Defining function pointer type
int call_fun(int a){
int result = 0;
HMODULE fundll = LoadLibrary("fun.dll"); // Calling into the dll
if(fundll){
fun* call_fun = (fun*) GetProcAddress(fundll, "fun"); // Getting exported function
if(call_fun){
result = call_fun(a); // Calling the exported fun with function pointer
}
}
return result;
}https://stackoverflow.com/questions/71969281
复制相似问题