下面我们实现自己的dll,并且利用一个测试案例展示使用方法
第一部分:开发dll
注:环境:vs2010编译器
新建win32 dll项目:
新建一个头文件,和项目同名
在dll2.h里添加:
#ifndef DLL2_API
#define DLL2_API _declspec(dllimport)
#endif
DLL2_API int add(int a,int b);
DLL2_API int subtract(int a,int b);
class DLL2_API Point
{
public:
Point(int x,int y);
~Point();
int GetX() const;
int GetY() const;
void Set(int x,int y);
private:
int m_x;
int m_y;
};
在dll2.cpp里添加:
// dll2.cpp : 定义 DLL 应用程序的导出函数。
#pragma once
#define DLL2_API _declspec(dllexport)
#include "stdafx.h"
#include "Dll2.h"
int add(int a,int b)
{
return a+b;
}
int subtract(int a,int b)
{
return a-b;
}
Point::Point(int x,int y)
{
this->m_x=x;
this->m_y=y;
}
Point::~Point()
{
}
int Point::GetX() const
{
return this->m_x;
}
int Point::GetY() const
{
return this->m_y;
}
void Point::Set(int x,int y)
{
this->m_x=x;
this->m_y=y;
}
编译执行(或生成)
此时在debug目录下:
我们要的就是dll2.dll和dll2.lib文件以及我们自己创建的dll2.h文件
第二部分:测试案例
下面我们来测试刚才开发的dll
步骤:
1.新建一个win32控制台工程
2.将刚才生成的三个文件(dll2.h dll2.lib dll2.dll)copy到当前执行路径下
3.添加内容如下:
// dll2Test.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <process.h>
#include "dll2.h"
#pragma comment(lib,"dll2.lib")
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
cout<<add(1,2)<<endl;
cout<<subtract(2,1)<<endl;
Point *pt=new Point(10,20);
cout<<"x="<<pt->GetX()<<endl;
cout<<"y="<<pt->GetY()<<endl;
pt->Set(20,10);
cout<<"x="<<pt->GetX()<<endl;
cout<<"y="<<pt->GetY()<<endl;
system("pause");
return 0;
}
截图: