使用C++調用C++ dll的關鍵步驟

來源:互聯網
上載者:User

被調用的dll項目

/*dllDemo.h中*/
extern "C" _declspec(dllexport) void Func(void); //介面函式宣告

/*dllDemo.cpp中*/
#include "dllDemo.h"
extern "C" _declspec(dllexport)void Func(void)    //介面函數定義
{
    return;
}

_declspec,Declare Specification,這個關鍵字可以理解為聲明規範。它有許多用法,文法如下:

__declspec ( extended-decl-modifier-seq )

配合dllexport和dllimport,分別表示匯入和到匯出dll介面函數。

 

調用dll的項目 - 顯式調用

1)只需要dll檔案

2)在調用處用法如下

代碼// a)聲明一個和dll介面函數規則相同的函數指標
typedef void(*pFunc)(void); 
pFunc doFunc=NULL;
// b)載入動態連結程式庫dll檔案;
HINSTANCE hDLL;
hDLL = LoadLibrary("dllDemo.dll"); 
// c)本地函數指標獲得dll中的介面函數;
doFunc=(pFunc)GetProcAddress(hDLL,"Func"); 
// d)調用
if(doFunc)
{
    doFunc();
}

3)調用完畢可以使用Freelibrary(hDLL)釋放dll檔案。 

 

調用dll的項目 - 隱式調用

1)需要dll

2)需要lib,並且在項目依賴項中添加 

3)調用處代碼如下 

//a) cpp頭部聲明來自dll的外部介面函數,函數名必須一樣。
extern "C"_declspec(dllimport) void Func(void);

int main()
{
    //b) 像使用其他函數一樣使用dll介面函數
    Func();

    return 0;
}

 4)運行期間無法釋放dll。

 

整理自:http://www.cnblogs.com/beer/archive/2010/08/19/1803560.html 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.