What Exporting Really
Means (dll匯出的本質)
The only truly interesting thing I introduced in the previous section
was the __declspec(dllexport)
modifier. When Microsoft's C/C++
compiler sees this modifier before a variable, function prototype, or C++ class,
it embeds some additional information in the resulting .obj file. The linker
parses this information when all the .obj files for the DLL are linked.
當編譯器在變數,函數原型,類前面發現有__declspec(dllexport)
時,編譯器會嵌入一些額外的資訊到產生的obj檔案裡。
linker在link的時候會解析並處理這些額外的資訊。
When the DLL is linked, the linker detects this embedded
information about the exported variable, function, or class and automatically
produces a .lib file. This .lib file contains the list of symbols exported by
the DLL.
linker發現了編譯器插入到這些匯出變數的資訊後,會根據這些資訊產生一個.lib檔案,.lib檔案大家都很熟悉,這個檔案主要儲存的是
dll的匯出符號表。
This .lib file is, of course, required to link any executable module
that references this DLL's exported symbols. In addition to creating the .lib
file, the linker embeds a table of exported symbols in the resulting DLL file.
This export section
contains the list (in alphabetical
order) of exported variables, functions, and class symbols. The linker also
places the relative virtual address (RVA), indicating where each symbol can be
found in the DLL module.
.lib檔案在link的時候是必須的,此外,linker還嵌入了匯出符號表 到產生的DLL檔案裡。這個匯出塊包含了這個dll所匯出的變數,函數,類。linker還將每個符號的相對的虛擬位移地址放到dll檔案裡,這樣每個符號都可以從這個dll模組被找到。
Using the Microsoft Visual Studio DumpBin.exe utility (with the -exports
switch), you can see what a
DLL's export section looks like。
使用vs的 dumpbin工具即可查看一個dll的匯出塊。
What Importing Really
Means (匯入的真正含義)
The previous section
introduced the __declspec(dllimport)
modifier. When you import a symbol, you do not have to use the __declspec(dllimport)
keyword—you can
simply use the standard C extern
keyword.
實際上,當你想匯入一個符號時,你不需要用到 __declspec(dllimport). 用extern就可以了。
However, the compiler can produce slightly more efficient code if it
knows ahead of time that the symbol you are referencing will be imported from a
DLL's .lib file. So I highly recommend that you use the __declspec(dllimport)
keyword for imported function and
data symbols. Microsoft does this for you when you call any of the standard
Windows functions.
但是,如果用__declspec(dllimport)
的話,編譯器會產生更有效率的代碼。
When the linker resolves the imported symbols, it embeds a special
section called the import section
in the resulting
executable module. The import section lists the DLL modules required by this
module and the symbols referenced from each DLL module.
linker解析匯入符號時,會嵌入一個匯入塊到產生的可執行模組裡。這個匯入塊包含了這個模組需要的所有dll和跟這些dll有聯關的匯入符號
Using Visual Studio's DumpBin.exe utility (with the -imports
switch), you can see what a
module's import section looks like.
用 DumpBin.exe 工具 (with the -imports
選項), 你可以獲得一個模組的匯入塊