dllimport 和 dllexport

发布时间 2023-11-09 09:43:44作者: strive-sun

Dll 在需要暴露接口的头文件里添加 dllexport 声明,比如,

#define DllExport   __declspec( dllexport )

class DllExport C {
   int i;
   virtual int func( void ) { return 1; }
};

  

注意,禁止对可导出类的成员显式使用 dllimport 和 dllexport 特性。

我们一般情况下会使用预定义宏控制 dll 接口的导入导出,比如,

#include <stdint.h>

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

#ifdef __PROJECT_OS_WIN32__
#define PROJECT_API __stdcall
#define DLLIMPORT_C extern __declspec(dllimport)
#define DLLEXPORT_C __declspec(dllexport)
#else
#define PROJECT_API
#define DLLIMPORT_C
#define DLLEXPORT_C __attribute__((visibility("default")))
#endif // __PROJECT_OS_WIN32__

#ifdef __PROJECT_SOURCE__
#define PROJECT_EXPORT DLLEXPORT_C
#else
#define PROJECT_EXPORT DLLIMPORT_C
#endif // __PROJECT_SOURCE__

PROJECT_EXPORT int PROJECT_API project_init(struct xxx**ctx, int x);

  

这样,我们只要在 Dll 的工程里添加 __PROJECT_OS_WIN32__ 和 __PROJECT_SOURCE__ 预定义宏就可以导出 project_init 接口

同样,我们在使用的时候只要在项目中添加 __PROJECT_OS_WIN32__  即可导入 project_init 接口,当然,项目中要包含相关接口的头文件

参考:

拓展:

上述第二个链接中提到了 .def 文件,添加该文件也是为了暴露接口,后续可以研究研究