创建DLL详解(2)

来源:互联网 发布:苹果6韩版支持什么网络 编辑:程序博客网 时间:2024/06/16 16:36

上一篇中我们讲到DLL导出函数的使用,这一篇我们讲下DLL导出类的使用
首先创建工程
这里写图片描述
这里写图片描述
选择DLL类型
这里写图片描述
创建工程完成后
这里写图片描述
这里DLLClass.h是我手动添加的
其实这里导出类的创建也很简单
直接再类的前面加上_declspec(dllexport)
例如class _declspec(dllexport) People
{
public:
People();
~People();
}
DLLClass.h

#ifndef _DLLCLASS_H#define _DLLCLASS_H#ifdef DLLEXPORT#define AMB _declspec(dllexport)#else#define AMB#endif#include <string>#include <iostream>using namespace std;class AMB People{public:    People(char* name, int age);    ~People();    bool SetName(char* name);    char* GetName();    bool SetAge(int age);    int GetAge();    void SelfIntroduction();private:    char m_name[50];    int m_age;};#endif

DLLClass.cpp

#include "stdafx.h"#define DLLEXPORT#include "DLLClass.h"People::People(char* name, int age){    strcpy_s(m_name, 50, name);    m_age = age;}People::~People(){}bool People::SetName(char* name){    strcpy_s(m_name, 50, name);    return true;}char* People::GetName(){    return m_name;}bool People::SetAge(int age){    m_age = age;    return true;}int People::GetAge(){    return m_age;}void People::SelfIntroduction(){    cout << "I am " << m_name << endl;    cout << "I am " << m_age << " years old" << endl;}

好了DLLClass.dll创建完成,我们用个工程来测试下
这里写图片描述
这里写图片描述
DLLTest.cpp

#include "stdafx.h"#include "DLLClass.h"#pragma comment(lib,"DLLClass.lib")int _tmain(int argc, _TCHAR* argv[]){    People s("lihua",20);    s.SelfIntroduction();    cout << s.GetName() << " " << s.GetAge()<<endl;    s.SetName("lilei");    s.SetAge(21);    cout << s.GetName() << " " << s.GetAge() << endl;    s.SelfIntroduction();    system("pause");    return 0;}

有一点要说明的是也可以像下面这样写

#ifdef DLLEXPORT#define AMB _declspec(dllexport)#else#define AMB _declspec(dllimport)#endif

如果不定义dllimport就无法使用静态成员变量,不过静态变量一般不常用,所以,一般也不写
运行
这里写图片描述
OK,类可以使用