先描述下dll的建立方法
test.h和test.cpp
[cpp]view plain
copy
?#pragma once
#ifdef __common
#define __common_export __declspec(dllexport)
#else
#define __common_export __declspec(dllimport)
#endif
extern
"c"__common_export
int__cdecl testfunc1(
inta,
intb);
class
__common_export myclass;
test.cpp
[cpp]view plain
copy
?#include "test.h"
inttestfunc2(
inta,
intb)
inttestfunc1(
inta,
intb)
intmyclass::addfunc(
inta,
intb)
生成了common.dll和common.lib檔案
使用方法,新建工程
[html]view plain
copy
?#include
<
iostream
>
#include <
windows.h
>
#include <
winbase.h
>
#include "../commondll/test.h"
using namespace std;
#pragma comment(lib,"commondll")
int main()
對於dll的引用,有兩種方法
第一種方法:使用loadlibrary和getprocaddress配合,這種方法稱為弱引用,其優點是 可以跨編譯器使用,也就是用vs2008編譯的dll,使用時候,到vs2010下**可以直接用。 缺點是 不能使用匯出的類
第二種方法:引用commondll.lib來引用,這種方法的優缺點就和 弱應用剛好互補,優點是使用方便,可以使用匯出的類,缺點是 vs2008編譯出來的lib,到vs2010或者其他版本的編譯器就有可能不能使用。
[cpp]view plain
copy
?#ifdef __common
#define __common_export __declspec(dllexport)
#else
#define __common_export __declspec(dllimport)
#endif
這種方法對於強引用來說,在編譯commondll.dll時候,在預處理器裡定義了巨集__common,這樣就會匯出對應的函式和類
當引用commondll.lib時候,沒有定義__common,__common_export就成了dllimport,它就會把lib匯出的函式匯入
強引用和弱引用
weak 和 strong 會出現在宣告中 預設情況下,乙個指標都會使用 strong 屬性,表明這是乙個強引用。這意味著,只要引用存在,物件就不能被銷毀。這是一種所期望的行為 當所有 強 引用都去除時,物件才能被收集和釋放。不過,有時我們卻希望禁用這種行為 一些集合類不應該增加其元素的引用,因為這...
弱引用和強引用
如果目標檔案對外部目標檔案符號進行強引用,但在鏈結成可執行檔案時不能被正確的決議 好奇怪的名稱,看看p 51 鏈結器就會報錯,這是對於強引用 strong reference 而言的。與之相對應還有一種弱引用 weak reference 在處理弱引用時,如果該符號有定義,則鏈結器將對該符號的引用進...
C 強引用和弱引用
鏈結器處理強引用和弱引用的過程幾乎是一樣的,只是對於未定義的弱引用,鏈結器不認為它是乙個錯誤,一般預設其為 0 位址為 0 或者是乙個特殊的值,以便程式 能夠識別。attribute weak extern int a printf a d n a 我們可以將它編譯成乙個可執行檔案,gcc 並不會報...