首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >__declspec(dllexport)和__declspec(dllimport)在C++中

__declspec(dllexport)和__declspec(dllimport)在C++中
EN

Stack Overflow用户
提问于 2022-04-22 13:07:43
回答 1查看 456关注 0票数 0

我经常在Windows上看到__declspec(dllexport) / __declspec(dllimport)指令,在Linux上看到带有函数的__attribute__((visibility("default"))),但我不知道为什么。你能向我解释一下,为什么我需要对共享库使用这些指令?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-04-22 16:43:45

当您需要从Dll调用函数时(通过导出它),可以从应用程序访问该函数时,将使用__declspec(dllexport)

示例这是一个名为"fun.dll“的dll:

代码语言:javascript
复制
// 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“中的”乐趣“:

代码语言:javascript
复制
#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;
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71969281

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档