C++封裝DLL,匯出一個類
阿新 • • 發佈:2019-01-10
首先:建一個DLL工程,win32專案--DLL--確定;
在標頭檔案中定義要匯出的類:
- class _declspec(dllexport) CWordSegment
- {
- public:
- CWordSegment();
- ~CWordSegment();
- bool CWordSegmentInit();
- char *CWordSegmentResolve();
- };
在相應的.cpp檔案中實現:
- #include "CWordSegment.h"
- #include
-
CWordSegment::CWordSegment()
- {
- printf("CWordSegment constructed /n");
- }
- CWordSegment::~CWordSegment()
- {
- printf("CWordSegment disconstructed /n");
- }
- bool CWordSegment::CWordSegmentInit()
- {
- printf("CWordSegmentInit /n");
- returntrue;
- }
- char* CWordSegment::CWordSegmentResolve()
- {
-
printf("CWordSegmentResolve /n"
- return NULL;
- }
三、編譯原始檔(快捷鍵F7),在../CWordSegment/Debug目錄下生成DLL的兩個最終要的檔案,這個應該不用解釋了吧
CWordSegment.dll
CWordSegment.lib
就此,DLL就搞好了,
下面如何呼叫這個lib檔案:
也很簡單:建一個測試工程控制檯應用程式:
然後把上面生產的庫檔案加進來,可以用相對路徑也可以用絕對路徑;這個隨便;
一般相對路徑加入的方法:
(1)連結器-->常規-->附加依賴目錄 加入進來即可;
(2)連結器-->常規-->附加依賴項 加入lib庫名稱;
然後就是匯出類:
- 原始碼檔案:testDll.h
- 此處宣告匯入類,把第一節CWordSegment.h檔案中的類定義COPY過來,
- 然後把匯出改為匯入,即更改巨集:
- 由_declspec(dllexport) 匯出巨集--->> 改為
- --->>> _declspec(dllimport) 倒入巨集
- 很簡單吧 :)
- */
- class _declspec(dllimport) CWordSegment
- {
- public:
- CWordSegment();
- ~CWordSegment();
- bool CWordSegmentInit();
- char *CWordSegmentResolve();
- };
測試程式如下:
- // testDll.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include "testDll.h"
- CWordSegment test;
- int main(int argc, char* argv[])
- {
- test.CWordSegmentInit();
- printf("Hello World!/n");
- return 0;
- }
首先:建一個DLL工程,win32專案--DLL--確定;
在標頭檔案中定義要匯出的類:
- class _declspec(dllexport) CWordSegment
- {
- public:
- CWordSegment();
- ~CWordSegment();
- bool CWordSegmentInit();
- char *CWordSegmentResolve();
- };
在相應的.cpp檔案中實現:
- #include "CWordSegment.h"
- #include
- CWordSegment::CWordSegment()
- {
- printf("CWordSegment constructed /n");
- }
- CWordSegment::~CWordSegment()
- {
- printf("CWordSegment disconstructed /n");
- }
- bool CWordSegment::CWordSegmentInit()
- {
- printf("CWordSegmentInit /n");
- returntrue;
- }
- char* CWordSegment::CWordSegmentResolve()
- {
- printf("CWordSegmentResolve /n");
- return NULL;
- }
三、編譯原始檔(快捷鍵F7),在../CWordSegment/Debug目錄下生成DLL的兩個最終要的檔案,這個應該不用解釋了吧
CWordSegment.dll
CWordSegment.lib
就此,DLL就搞好了,
下面如何呼叫這個lib檔案:
也很簡單:建一個測試工程控制檯應用程式:
然後把上面生產的庫檔案加進來,可以用相對路徑也可以用絕對路徑;這個隨便;
一般相對路徑加入的方法:
(1)連結器-->常規-->附加依賴目錄 加入進來即可;
(2)連結器-->常規-->附加依賴項 加入lib庫名稱;
然後就是匯出類:
- 原始碼檔案:testDll.h
- 此處宣告匯入類,把第一節CWordSegment.h檔案中的類定義COPY過來,
- 然後把匯出改為匯入,即更改巨集:
- 由_declspec(dllexport) 匯出巨集--->> 改為
- --->>> _declspec(dllimport) 倒入巨集
- 很簡單吧 :)
- */
- class _declspec(dllimport) CWordSegment
- {
- public:
- CWordSegment();
- ~CWordSegment();
- bool CWordSegmentInit();
- char *CWordSegmentResolve();
- };
測試程式如下:
- // testDll.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include "testDll.h"
- CWordSegment test;
- int main(int argc, char* argv[])
- {
- test.CWordSegmentInit();
- printf("Hello World!/n");
- return 0;
- }