實現一個簡單的DLL動態鏈接庫提供調用
在書上看到將c++類打包成DLL提供調用,自己也寫了個很簡單的程序。(VC++6.0的集成開發平臺)
實現一個DLL動態鏈接庫,先創建一個“Win32 Dynamic-Link Library”工程,工程名為“MathDLL”。選擇創建一個“空”的工程。
編寫頭文件:SimpleMath.h 代碼如下:
#ifndef _SimpleMath_Include
#define _SimpleMath_Include
class SimpleMath
{
public:
int _declspec(dllexport) Add(int a, int b);
int _declspec(dllexport) Reduce(int a, int b);
};
#endif
在編寫如下的SimpleMath.cpp文件:
#include "SimpleMath.h"
int SimpleMath::Add(int a, int b)
{
return a+b;
}
int SimpleMath::Reduce(int a, int b)
{
return a-b;
}
執行“Build”構建菜單,將在MathDLL\Debug目錄下生成MathDLL.lib和MathDLL.dll兩個文件。
現在在創建一個控制臺程序來調用MathDLL.dll中兩個類成員函數(Add 、Reduce)。
創建一個“Win32 Console Application”工程,工程名為“TestDLL”,選擇創建一個“空”工程。
#include <stdio.h>
#include "..\MathClass\SimpleMath.h"
void main()
{
SimpleMath *result = new SimpleMath();
printf("10+20的值為:%d\n",result->Add(10,20));
printf("30-10的值為:%d\n",result->Reduce(30,10));
}
注意:要調用MathDLL.dll動態鏈接庫,還要執行“工程->設置”在“連接”中輸入MathDLL.lib文件的路徑:..\MathDLL\Debug\MathDLL.lib。
在這里我運行的時候顯示計算機丟失MathDLL.dll文件,原因是因為找不到“MathDLL.dll動態庫文件“。只需把剛剛生成的MathDLL.lib文件拷貝到當前應用程序目錄中就可以了。
浙公網安備 33010602011771號