DLL入門系列三

來源:互聯網
上載者:User

為了便於學習,本系列文章轉載於http://www.cppblog.com/suiaiguo/archive/2009/07/20/90619.html,如果需要轉載,請註明轉載原網址。

前面介紹了怎麼從DLL中匯出函數,下面我們來看一下如何從DLL中匯出變數來。

   聲明為匯出變數時,同樣有兩種方法:
   第一種是用__declspec進行匯出聲明

 

#ifndef _DLL_SAMPLE_H
#define _DLL_SAMPLE_H

// 如果定義了C++編譯器,那麼聲明為C連結方式
#ifdef __cplusplus
extern "C" {
#endif

// 通過宏來控制是匯入還是匯出
#ifdef _DLL_SAMPLE
#define DLL_SAMPLE_API __declspec(dllexport)
#else
#define DLL_SAMPLE_API __declspec(dllimport)
#endif

// 匯出/匯入變數聲明
DLL_SAMPLE_API extern int DLLData;

#undef DLL_SAMPLE_API

#ifdef __cplusplus
}
#endif

#endif

 

 

  第二種是用模組定義檔案(.def)進行匯出聲明

 

LIBRARY DLLSample
DESCRIPTION "my simple DLL"
EXPORTS
        DLLData DATA  ;DATA表示這是資料(變數)

 

 

   下面是DLL的實現檔案

#include "stdafx.h"
#define _DLL_SAMPLE

#ifndef _DLL_SAMPLE_H
#include "DLLSample.h"
#endif

#include "stdio.h"

int DLLData;

//APIENTRY聲明DLL函數進入點
BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
 switch (ul_reason_for_call)
 {
  case DLL_PROCESS_ATTACH:
      DLLData = 123;  // 在入口函數中對變數進行初始化
      break
  case DLL_THREAD_ATTACH:
  case DLL_THREAD_DETACH:
  case DLL_PROCESS_DETACH:
   break;
 }
 return TRUE;
}

 

同樣,應用程式調用DLL中的變數也有兩種方法。
第一種是隱式連結:

 

#include <stdio.h>
#include "DLLSample.h"

#pragma comment(lib,"DLLSample.lib")


int main(int argc, char *argv[])
{
 printf("%d ", DLLSample);
 return 0;
}

 

 
第二種是顯式連結:

 

#include <iostream>
#include <windows.h>

int main()
{
        int my_int;
        HINSTANCE hInstLibrary = LoadLibrary("DLLSample.dll");

        if (hInstLibrary == NULL)
        {
         FreeLibrary(hInstLibrary);
        }
        my_int = *(int*)GetProcAddress(hInstLibrary, "DLLData");
        if (dllFunc == NULL)
        {
         FreeLibrary(hInstLibrary);
        }
        std::cout<<my_int;
        std::cin.get();
        FreeLibrary(hInstLibrary);
        return(1);
}

 

 

通過GetProcAddress取出的函數或者變數都是地址,因此,需要解引用並且轉類型。


 

聯繫我們

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