先描述下dll的創建方法
Test.h和Test.cpp
#pragma once #ifdef __COMMON #define __COMMON_EXPORT __declspec(dllexport) #else #define __COMMON_EXPORT __declspec(dllimport) #endif extern "C" __COMMON_EXPORT int __cdecl testFunc1(int a,int b); class __COMMON_EXPORT MyClass{ public: int addFunc(int a,int b); };#include "test.h" int testFunc2(int a,int b){ return a+b; } int testFunc1(int a,int b){ return testFunc2(a,b); } int MyClass::addFunc(int a,int b){ return a+b; }
使用方法,新建工程
#include <iostream> #include <Windows.h> #include <WinBase.h> #include "../CommonDll/test.h" using namespace std; #pragma comment(lib,"CommonDll") int main(){ //弱引用dll,弱引用dll不能使用導出的類 // HMODULE module=LoadLibraryA("CommonDll.dll"); // typedef int (*func)(int,int); // func f=(func)GetProcAddress(module,"testFunc1"); //強引用dll int a=testFunc1(2,5); cout<<a<<endl; MyClass cat; cout<<cat.addFunc(6,7)<<endl; } 第一種方法:使用LoadLibrary和GetProcAddress配合,這種方法稱為弱引用,其優點是 可以跨編譯器使用,也就是用vs2008編譯的dll,使用時候,到vs2010下代碼可以直接用。 缺點是 不能使用導出的類
第二種方法:引用CommonDll.lib來引用,這種方法的優缺點就和 弱應用剛好互補,優點是使用方便,可以使用導出的類,缺點是 vs2008編譯出來的lib,到vs2010或者其他版本的編譯器就有可能不能使用。
#ifdef __COMMON #define __COMMON_EXPORT __declspec(dllexport) #else #define __COMMON_EXPORT __declspec(dllimport) #endif
這種方法對于強引用來說,在編譯CommonDll.dll時候,在預處理器里定義了宏__COMMON,這樣就會導出對應的函數和類
當引用CommonDll.lib時候,沒有定義__Common,__COMMON_EXPORT就成了dllimport,它就會把lib導出的函數導入
查看更多
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。