2013-10-15 137 views
2

的iCLASS(我的界面)输出类:使用接口从DLL

#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 

Class.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 

Class.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>(); (因为它不允许创建抽象类的对象)

我该如何解决这个问题,这是最好的做法?

+1

可能重复[如何从一个DLL导出一个C++类?(http://stackoverflow.com/questions/6840576/how-to-export-ac-class-from-a -dll) –

+0

如果您导出(和导入)类,并且包含相关头文件,程序将编译并工作。由于您没有说明您的目标或限制,因此无法说这是否是好的做法。 –

+0

@DavidHeffernan:查看我的帖子编辑 – leon22

回答

1

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

How to implement the factory pattern in C++ correctly