使用接口从 dll 导出类

Using interface to export class from dll

本文关键字:dll 接口      更新时间:2023-10-16

IClass (My interface):

#ifndef _ICLASS_H
#define _ICLASS_H
#include <sstream>
namespace Test
{
    class __declspec(dllexport) IClass
    {
    public:     
        virtual ~IClass() {}                
        virtual bool Init(const std::string &path) = 0;     
    };
}
#endif

类.h

#ifndef _CLASS_H
#define _CLASS_H
#include "IClass.h"
#include <memory>
#include <sstream>
#include <stdio.h>
namespace Test
{
    class Class: public IClass
    {
    public:
        Class();
        ~Class();               
        bool Init(const std::string &path);         
    };
}
#endif

类.cpp

#include "Class.h"
namespace Test
{
    Class::Class()
    {       
    }
    bool Class::Init(const std::string &path)
    {
        try
        {
            // do stuff
            return true;
        }
        catch(std::exception &exp)
        {
            return false;
        }
    }   
}

(在 exe 中,DLL 隐式链接)

#include "IClass.h"
using namespace Test;
int main(int argc, char* argv[])
{
    std::shared_ptr<IClass> test = std::make_shared<Class>(); // error: unreferenced Class
    test->Init(std::string("C:\Temp"));
}

目前尚未声明类

->如果我将Class.h包含在主要内容中,则会发生以下错误: LNK2019: unresolved external symbol:添加class __declspec(dllexport) Class : public IClass解决此链接器问题,但是可以这样做吗?

-> 我也不能这样做:std::shared_ptr<IClass> test = std::make_shared<IClass>();(因为不允许创建抽象类的对象)

我该如何解决此问题,这是最佳实践吗?

如果您希望 EXE 分配新的"类"对象,EXE 代码必须知道类类型。如果要使 EXE 中的类类型保持未知,一种解决方案可能是从 DLL 导出一个工厂函数,该函数将构造一个 Class 对象并将其作为 IClass 指针返回。

请参阅如何在C++中正确实现工厂模式