因为项目合作的关系,需要将源代码转化为DLL。原本以为会很复杂,结果试验了一下,简单的吓人。

(1)编译类的DLL。

打开Visual Studio,文件→新建→项目→Win32 控制台应用程序,设置项目名称为MyDLL,应用程序类型选择DLL(D),附加选项选择空项目(E)。

头文件如下所示:

/*****************************************************************************
*                                                                            *
*  File: MyDLL.h                                                             *
*  Author: zhuxiaoyang (cgnerds@gmail.com)                                   *
*                                                                            *
*  Created on July 5th, 2013, AM 11:00                                       *                                  *
*                                                                            *
*****************************************************************************/
#ifndef __MyDLL_H__
#define __MyDLL_H__

#if _MSC_VER // this is defined when compiling with Visual Studio
#define EXPORT_API __declspec(dllexport) // Visual Studio needs annotating exported functions with this
#else
#define EXPORT_API // Other IDE does not need annotating exported functions, so define is empty
#endif

#include <iostream>
using namespace std;

class EXPORT_API MyClass
{
public:
	MyClass(int a, int b);
	~MyClass();
	void show();

private:
	int member_a;
	int member_b;
};

#endif __MyDLL_H__
源文件如下所示:

/*****************************************************************************
*                                                                            *
*  File: MyDLL.cpp                                                           *
*  Author: zhuxiaoyang (cgnerds@gmail.com)                                   *
*                                                                            *
*  Created on July 5th, 2013, AM 11:00                                       *                                  *
*                                                                            *
*****************************************************************************/
#include "MyDLL.h"

MyClass::MyClass(int a, int b)
{
	member_a = a;
	member_b = b;
}

MyClass::~MyClass()
{
}

void MyClass::show()
{
	cout<<"member_a: "<<member_a<<", member b: "<<member_b<<endl;
}
编译后,会生成MyDLL.lib和MyDLL.dll两个文件。

(2)调用类的DLL。

打开Visual Studio,文件→新建→项目→Win32 控制台应用程序,设置项目名称为MyDLLTest,应用程序类型选择控制台应用程序(O),附加选项选择空项目(E)。

在项目属性里,链接器→常规→附加库目录,填写MyDLL.lib所在目录;输入里填写MyDLL.lib。将MyDLL.dll放入工作目录,也就是生成MyDLLTest.exe的地方。

源文件如下所示:

#include "MyDLL.h"
#include <iostream>
using namespace std;

int main()
{
	MyClass myClass(5, 6);
	myClass.show();

	system("pause");
	return 0;
}
运行程序,会出现如下结果:





Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐