封装C++项目为dll

这是头文件,定义了一个接口类 IMyInterface。

#pragma once

#ifndef MY_INTERFACE_H
#define MY_INTERFACE_H
#define _CRT_SECURE_NO_WARNINGS

#define MY_DLL_API __declspec(dllexport)  // 定义导出到DLL中的宏

// 接口类,用于导出到DLL
class MY_DLL_API IMyInterface
{
public:
    static IMyInterface* CreateInstance();  // 静态成员函数,用于创建接口实例

    virtual void Initialize() = 0;  // 纯虚函数,必须在派生类中实现
    virtual void Cleanup() = 0;     // 纯虚函数,必须在派生类中实现
    virtual char* GetLabel() = 0;   // 纯虚函数,必须在派生类中实现
};

#endif

这是实现上述接口的源文件,其中实现了一个具体类 MyHelloClass。

#include "Interface.h"
#include <iostream>
#include <cstring>  // 包含cstring库以使用memset和strcpy函数

// 具体类,实现接口IMyInterface
class MyHelloClass : public IMyInterface
{
public:
    MyHelloClass();  // 构造函数

    virtual void Initialize();  // 实现初始化函数
    virtual void Cleanup();     // 实现清理函数
    virtual char* GetLabel();   // 实现获取标签函数

private:
    char Label[1024];  // 存储标签的数组
};

// 构造函数,初始化Label数组
MyHelloClass::MyHelloClass()
{
    memset(Label, 0, 1024);     // 将Label数组初始化为全零
    strcpy(Label, "Hello");     // 将字符串"Hello"复制到Label数组中
}

// 初始化函数
void MyHelloClass::Initialize()
{
    printf("MyHelloClass::Initialize() \n");  // 打印初始化消息
}

// 清理函数
void MyHelloClass::Cleanup()
{
    printf("MyHelloClass::Cleanup() \n");  // 打印清理消息
}

// 获取标签函数,返回Label数组的指针
char* MyHelloClass::GetLabel()
{
    return Label;
}

// 实现静态成员函数,返回MyHelloClass实例的新对象
IMyInterface* IMyInterface::CreateInstance()
{
    return new MyHelloClass();
}

test demo

#include <iostream>
#include "libdll/Interface.h"  // 包含生成的头文件

#pragma comment(lib,"dll.lib")
int main()
{
	// 创建接口的实例
	IMyInterface* myInterface = IMyInterface::CreateInstance();

	if (myInterface)
	{
		// 调用初始化方法
		myInterface->Initialize();

		// 获取并打印标签
		char* label = myInterface->GetLabel();
		std::cout << "Label: " << label << std::endl;

		// 调用清理方法
		myInterface->Cleanup();

		// 释放实例
		delete myInterface;
	}
	else
	{
		std::cerr << "Failed to create interface instance." << std::endl;
	}

	return 0;
}
posted @ 2024-07-14 16:49  小马同学..3  阅读(62)  评论(0)    收藏  举报