C++ 動態連結程式庫

來源:互聯網
上載者:User

動態連結程式庫兩種使用方法

1. Dll

  .h檔案 

#ifdef DLL1_API
#else
#define DLL1_API _declspec(dllimport)
#endif
DLL1_API int Add(int a,int b);
DLL1_API int Sub(int a,int b);
class DLL1_API Point
{
public:
    void Output(int x,int y);
};

 

  .cpp檔案

#define DLL1_API _declspec(dllimport)
#include "Dll1.h"
#include <windows.h>
#include <stdio.h>
int Add(int a,int b)
{
    return a+b;
}
int Sub(int a,int b)
{
  return a-b;
}
void Point::Output(int x,int y)
{
   HWND hwnd;
   hwnd=GetForegroundWindow();
   HDC hdc=GetDC(hwnd);
   char buf[20];
   memset(buf,0,20);
   sprintf(buf,"x=%d,y=%d",x,y);
   TextOut(hdc,0,0,buf,strlen(buf));
   ReleaseDC(hwnd,hdc);

}

調用Dll  把編譯產生的.dll和.lib檔案放在程式目錄下,把Dll的.h檔案也要拷貝到引用程式目錄下。Project->Setting->Link 設定 Object/library modules的lib檔案位置。如"Debug/Dll3.lib"。

添加引用檔案 #include "Dll1.h"

void CDllTestDlg::OnBtnAdd() 
{
    // TODO: Add your control notification handler code here
    CString str;
    str.Format("5+3=%d",Add(5,3));
    MessageBox(str);
}

void CDllTestDlg::OnBtnSub() 
{
    // TODO: Add your control notification handler code here
    CString str;
    str.Format("5-3=%d",Sub(5,3));
    MessageBox(str);
}

void CDllTestDlg::OnBtnOutput() 
{
    // TODO: Add your control notification handler code here
    Point pt;
    pt.Output(5,3);
}

二 .def方式 解決名字改編問題,不同的語言使用問題。

在程式目錄下建立個尾碼名為:def檔案,在Project->Add To Project\Files 添加到工程中。

dll

.def

LIBRARY Dll3
EXPORTS
Add

.cpp

 

int _stdcall Add(int a,int b)
{
   return a+b;

調用

.h

 

_declspec(dllimport) int _stdcall Add(int a,int b);

.cpp

void CDll3TestDlg::OnBTNAdd() 
{
    CString str;
    str.Format("5+3=%d",Add(5,3));
        MessageBox(str);
}

 

 以上調用的方式都是隱式連結方式載入方式實現對動態連結程式庫訪問

動態載入方式

void CDll3TestDlg::OnBTNAdd() 
{
    HINSTANCE hInst;//dll 控制代碼
    hInst=LoadLibrary("Dll3.dll");//動態載入Dll
    typedef int(_stdcall *lpAdd)(int,int);//定義函數指標類型
    lpAdd AddFun=(lpAdd)GetProcAddress(hInst,"Add");
    if(!AddFun)
    {
        MessageBox("擷取函數地址失敗!");
        return;
    }
    CString str;
    str.Format("5+3=%d",AddFun(5,3));
    FreeLibrary(hInst);//不需要訪問Dll,釋放
    MessageBox(str);
}

 

總結.def的方式能解決跨語言問題,個人比較推崇這種方法。歡迎留言,正在學習C++
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.