使用接口从 dll 导出类
Using interface to export class from dll
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++中正确实现工厂模式
相关文章:
- C++ 多个 DLL 之间的共享接口
- 可视化 使用 C++ API 注册 COM DLL 的所有接口
- 如何从MFC DLL中获取与COM包裹的C#对象的接口
- 使用抽象接口C++ dll 边界 -标头中的智能指针>?叫删除?
- 当从一个应用程序调用时,在DLL方法中创建COM接口指针是有效的,但当从另一个应用软件调用时则无效
- 如何在C#中使用C++DLL导出的接口指针
- Visual C++ 中 DLL 的 DLL 导出和接口
- 在主应用程序中声明的 dll 中实现接口 - C++
- 使用 ATL 编译 dll,并将方法参数作为接口,但将它们作为 coclass 获取
- 运算符=不是DLL中导出的C++__接口的成员
- 我的Java GUI与我的超酷专有dll接口.如何防止第三方与此 dll 接口
- 从可锁定容器的DLL接口隐藏Boost::互斥
- std::字符串流类需要有dll接口
- 如何使用c#中的参数BSTR*和BSTR**来调用遗留的c++ DLL接口方法?
- c++ DLL接口和内存
- 在dll接口中使用静态类时消除C4251警告的一种方法
- 导出DLL接口中包含相同类的STL类成员
- 如何在R中与DLL接口
- C++具有非虚拟析构函数的 DLL 接口类
- 如何在我的dll接口或ABI中使用标准库(STL)类