win32動態庫

(1)首先創建win32控制檯應用程序


(2)在【應用程序設置】->【應用程序類型】選擇“DLL(D)”



(3)在建立的工程中添加lib.h及lib.cpp文件,源代碼如下:

#ifndef LIB_H

 

#define LIB_H

 

extern "C" int __declspec(dllexport)add(int x, int y);

 

#endif

 

/* 文件名:lib.cpp */

 

#include "lib.h"

 

int add(int x, int y)

 

{

     return x + y;

}

 

(4)建立一個與DLL工程處於同一工作區的應用工程DllCall,它調用DLL中的函數add,其源代碼如下:

#include "stdafx.h"

#include <stdio.h>

#include <windows.h>

typedef int(*lpAddFun)(int, int); //宏定義函數指針類型

 

int main(int argc, char *argv[])

{

     HINSTANCE hDll; //DLL句柄

     lpAddFun addFun; //函數指針

     hDll = LoadLibrary("..\\Debug\\dllTest.dll");

     if (hDll != NULL)

     {

         addFun= (lpAddFun)GetProcAddress(hDll, "add");

         if (addFun != NULL)

         {

              intresult = addFun(2,3);

              printf("%d", result);

         }

         FreeLibrary(hDll);

     }

     return 0;

}

 

(5)運行代碼,結果如下所示:


 

下面介紹DLL如何導出類:

(1)在建立的Win32 DLL項目中建立導出類

//point.h

#ifndef POINT_H

#define POINT_H

#ifdef DLL_FILE

class _declspec(dllexport) point //導出類point

#else

class _declspec(dllimport) point //導入類point

#endif

 

{

public:

     float y;

     float x;

     point();

     point(float x_coordinate, float y_coordinate);

};

#endif

 

//point.cpp

#include "stdafx.h"

#ifndef DLL_FILE

#define DLL_FILE

#endif

#include "point.h"

//類point的缺省構造函數

point::point()

{

     x = 0.0;

     y = 0.0;

}

//類point的構造函數

point::point(float x_coordinate, float y_coordinate)

{

     x = x_coordinate;

     y = y_coordinate;

}

 

//circle.h

 

#ifndef CIRCLE_H

 

#define CIRCLE_H

 

#include "point.h"

 

#ifdef DLL_FILE

class _declspec(dllexport)circle //導出類circle

#else

class _declspec(dllimport)circle //導入類circle

#endif

{

public:

     void SetCentre(const point );

     void SetRadius(float r);

     float GetGirth();

     float GetArea();

     circle();

private:

     float radius;

     point centre;

};

#endif

 

//circle.cpp

#include "stdafx.h"

#ifndef DLL_FILE

#define DLL_FILE

#endif

#include "circle.h"

#define PI 3.1415926

//circle類的構造函數

circle::circle()

{

     centre = point(0, 0);

     radius =0;

}

//得到圓的面積

float circle::GetArea()

{

     return PI *radius * radius;

}

//得到圓的周長

float circle::GetGirth()

{

     return 2 *PI * radius;

}

//設置圓心座標

void circle::SetCentre(const point centrePoint)

{

     centre = centrePoint;

}

//設置圓的半徑

void circle::SetRadius(float r)

{

     radius = r;

}

(2)編譯生成dll文件。將生成的dll文件和lib文件拷貝到要調用此dll的工程中

調用代碼(靜態鏈接):

文件頭部加入

#include "../Win32DLL/circle.h"

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

調用

int main(int argc, char *argv[])

{

circle c;

     point p(2.0, 2.0);

     c.SetCentre(p);

     c.SetRadius(1.0);

     printf("area:%f girth:%f", c.GetArea(), c.GetGirth());

     return 0;

}

運行看結果即可

突然用到了,花了點時間,學會了


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章