dll实现(动态链接库)

下面我们实现自己的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;
}

 

截图:

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值