(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;
}
运行看结果即可
突然用到了,花了点时间,学会了