declspec(dllexport) _declspec(dllimport)

__declspec(dllexport) & __declspec(dllimport)


1.使用 __declspec(dllexport) 从 DLL 导出 

Microsoft 在 Visual C++ 的 16 位编译器版本中引入了 __export,使编译器得以自动生成导出名并将它们放到一个 .lib 文件中。然后,此 .lib 文件就可以像静态 .lib 那样用于与 DLL 链接.

2.声明一个导入函数,是说这个函数是从别的DLL导入。我要用。一般用于使用某个dll的exe中 

3.以下摘自<window核心编成>:

下面的头文件被DLL和EXE文件同时包括:

/***************************************************************************
Module:  MyLib.h
***************************************************************************/
#ifdef MYLIBAPI

// MYLIBAPI 应该在要导出的DLL文件中定义
// code modules before this header file is included.

// All functions/variables are being exported.

#else

//  当头文件被EXE文件引用此处定义EXE文件要导入的函数和变量
#define MYLIBAPI extern "C" __declspec(dllimport)

#endif

////////////////////////////////////////////////////////////////////////////

// Define any data structures and symbols here.

////////////////////////////////////////////////////////////////////////////

// 定义导出变量
MYLIBAPI int g_nResult;

////////////////////////////////////////////////////////////////////////////

// 此处定义导出函数原形
MYLIBAPI int Add(int nLeft, int nRight);

////////////////////////////// End of File /////////////////////////////////


/***************************************************************************
Module: MyLibFile1.cpp
***************************************************************************/


#include <windows.h>


// This DLL source code file exports functions and variables.
#define MYLIBAPI extern "C" __declspec(dllexport)

// Include the exported data structures, symbols, functions, and variables.
#include "MyLib.h"


// Place the code for this DLL source code file here.
int g_nResult;


int Add(int nLeft, int nRight) {
   g_nResult = nLeft + nRight;
   return(g_nResult);
}

MyLibFile1.cpp文件中的导出函数和变量前没有MYLIBAPI修饰原因是编辑器在解析头文件的时候会记住应该导出的函数和变量.


4.何为导出:

window编辑器在看到__declspec(dllexport)修饰的变量或者函数或类时候,会在生成的。OBJ 文件中嵌入一些额外的信息,当连接器在链接DLL所有OBJ文件时,会解析这些信息,并声称一个LIB文件,该LIB文件列出所有该DLL文件到处的符号(symbol),同时连接器还会在生成DLL文件中嵌入一个导出符号表(export section)

可以使用dumpbin.exe运行 查看DLL文件中的导出段



发布了18 篇原创文章 · 获赞 2 · 访问量 2万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章