c++ - std::stringstream 类需要有 dll 接口(interface)

标签 c++ c windows dll stringstream

我在 dll 中有一个 C++ 类。

在该类中,我想将 Curl 回调中的数据存储到成员变量中。 我打算像这样使用字符串流:

void MyClass::CurlCallback( void * pvData, size_t tSize )
{
    const char* data = static_cast<const char*>(pvData);

    m_myStringStream << sata;
}

但是当在我的类中声明 stringstream 时,如下所示:

private:
 std::stringstream m_myStringStream;

我收到以下错误:

Error   1   error C2220: warning treated as error - no 'object' file generated
Warning 2   warning C4251: 'MyClass::MyClass::m_myStringStream' : class     'std::basic_stringstream<_Elem,_Traits,_Alloc>' needs to have dll-interface to be used by clients of class 'MyClass::MyClass'

如何声明此字符串流而不出现此错误?

我认为这是因为 stringstream 是一个 C++ 变量,但 dll 需要 C 样式变量。

我已经研究过创建一个类来存储 xml 数据,如下所示:

    class XMLData
    {
    public:
        XMLData();
        virtual ~ XMLData();

        const char* GetXMLData() const { return xml; }
        void Append( const char* xmlData ) { /*add xmlData to xml blah blah*/};

    private:
        //Add more here - to do

        char* xml;
        int length;
    };

并声明它:

    XMLData* m_xmlData;

最好的方法是什么?

最佳答案

首先,您会收到警告,您选择威胁所有警告,例如项目设置中的错误。

DLL 导出类不应在其导出接口(interface)中声明复杂类型(如 STL 模板),因为它将 DLL 的使用限制为同一版本的编译器。这就是您收到警告的原因。

要解决这个问题,您应该仅导出一个接口(interface)类(即纯抽象类)并返回该接口(interface)的实现。

像这样:

//in the interface:
class DLL_API IMyClass
{
  public:
    virtual void set(const char* data)=0;
    virtual const char* get()=0;
}

//now not in the interface:
class CMyClass : public IMyClass
{
private: 
  std::stringstream mystream;
public:
   virtual void set(const char* data){
     mystream<<data;
   }
   virtual const char* get(){
        return mystream.str().c_str();
   }
}

并且您仅使用 DLL 外部的引用或指针,如果需要在可执行文件中创建对象,则需要 DLL 中的工厂方法,因为它只知道接口(interface)。

IMyClass* ObjectFactory::GetMyClass()
{
  return new CMyClass();
}

关于c++ - std::stringstream 类需要有 dll 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26158227/

相关文章:

c++ - 如何将输入 'three four + five six =' 转换为 '34+56' ?

c++ - Dllmain 可以使用 FreeLibrary 吗?

windows - golang : cross platform path. 目录

windows - 在添加/删除程序窗口中更新版本号

ruby - 在 Windows 上运行时无法退出 Guard

c++ - 在 Mac OS X 上使用 ffmpeg 和 Qt

c# - 在 C++ 和 C#/VB.NET 中使用环境变量搜索 ProgramFiles 和 ProgramFiles(x86)

c - qemu 的奇怪 C 数组行为

c - 读取数据文件,计算给定数据的总和

c++ - 类型转换一个物体两次 vs 一次性能