动态链接库(DLL)总结---从DLL中导出类(6)

     我们创建一个工程动态链接库,名称为DLL1,然后在DLL1.h中添加代码如下:

#ifdef DLL1_API_IMP 
#else
#define  DLL1_API_IMP  __declspec(dllimport) 
#endif


//导出类
class DLL1_API_IMP Test
{
public:
	void output(int x, int y);
};

   在DLL1.cpp中添加代码如下:

#include "stdafx.h"
#define  DLL1_API_IMP  __declspec(dllexport)
#include "DLL1.h"
#include <iostream>

void Test::output(int x, int y)
{
	std::cout << x + y<< std::endl;
}

  右键点击项目----选择重新生成。会发现生成DLL1.dll 和 DLL1.lib文件

   创建一个控制台项目,将DLL1.h 、DLL1.dll 和 DLL1.lib三个文件,拷贝到该项目下,添加代码如下:

#include "stdafx.h"
#include <Windows.h>

#pragma comment(lib,"DLL1.lib")
#include "DLL1.h"
int _tmain(int argc, _TCHAR* argv[])
{
	Test t;
	t.output(3, 2);

	system("pause");
	return 0;
}
  运行查看结果即可。


  在有些时候,我们可能不需要导出整个类,而是某些函数,那么我们可以将class后面的DLL1_API_IMP注释起来,在函数前面放置DLL1_API_IMP宏。此时,只导出output函数。为了进行测试,只导出output函数,我们在添加一个普通的函数test,代码如下

#ifdef DLL1_API_IMP 
#else
#define  DLL1_API_IMP  __declspec(dllimport) 
#endif


//导出类
class Test
{
public:
	void <span style="font-family: Arial, Helvetica, sans-serif;">DLL1_API_IMP  </span><span style="font-family: Arial, Helvetica, sans-serif;"> output(int x, int y);</span>
        void test();
};

cpp文件如下

#include "stdafx.h"
#define  DLL1_API_IMP  __declspec(dllexport)
#include "DLL1.h"
#include <iostream>

void Test::output(int x, int y)
{
	std::cout << x + y<< std::endl;
}

void Test::test()
{
	std::cout <<”... test ...“<< std::endl;
}
重新生成后,并将DLL1.h 、DLL1.dll 和 DLL1.lib三个文件,拷贝到测试项目下,添加代码如下:
#include "stdafx.h"
#include <Windows.h>

#pragma comment(lib,"DLL1.lib")
#include "DLL1.h"
int _tmain(int argc, _TCHAR* argv[])
{
	Test t;
	t.output(3, 2);
   //   t.test() //error
	system("pause");
	return 0;
}

运行测试即可。




  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值