如何使用TMemoryStrream编写和读取组件

时间:2016-06-09 18:03:02

标签: c++

我一直在尝试使用TComponent方法在TMemoryStream对象上编写一个从writecomponent派生的任意类的对象,并使用{{}再次检索此对象1}}方法。虽然我认为这是一项简单的任务,但我无法使其正常工作。实际上没有编译错误,但没有正确加载对象的属性。请帮我找到我做错了什么。这是我的代码段。

readcomponent

1 个答案:

答案 0 :(得分:0)

它不起作用,因为

  1. 您的Woman类没有任何__published读/写属性。 WriteComponent()ReadComponent()方法是DFM流系统的一部分,DFM依靠已发布属性的RTTI来完成其工作。

  2. DFM无法构造您的类的实例,因为它不是兼容的构造函数,您使用的是DFM无法调用的自定义构造函数。

  3. 您需要相应地更新课程,例如:

    class Woman : public TComponent
    {
    private:
        int fAge;
        UnicodeString fName;
    
    public:
        __fastcall Woman(TComponent* Owner)
            : TComponent(Owner)
        {
        }
    
        __fastcall Woman(TComponent* Owner, int InAge, const UnicodeString &InName)
            : TComponent(Owner)
        {
            fAge = InAge;
            fName = InName;
        }
    
    __published:
        __property int Age = {read=fAge, write=fAge};
        __property UnicodeString Name = {read=fName, write=fName};
    };
    

    然后你可以这样做:

    int _tmain(int argc, _TCHAR* argv[])
    {
        auto_ptr<Woman> FirstWoman(new Woman(NULL, 25, L"Anjelina"));
    
        auto_ptr<TMemoryStream> MStr(new TMemoryStream);
        auto_ptr<TStringStream> SStr(new TStringStream(L""));
    
        MStr->WriteComponent(FirstWoman.get());
        MStr->Position = 0;
        ObjectBinaryToText(MStr.get(), SStr.get());
        SStr->Position = 0;
        UnicodeString as = SStr->DataString;
    
        auto_ptr<TStringStream> pss(new TStringStream(as));
        auto_ptr<TMemoryStream> pms(new TMemoryStream);
    
        ObjectTextToBinary(pss.get(), pms.get());
        pms->Position = 0;
    
        auto_ptr<TComponent> pc(pms->ReadComponent(NULL));
        Woman* AWoman = static_cast<Woman*>(pc.get());
    
        cout << AWoman->Age << endl;
        cout << AWoman->Name.c_str() << endl;
    
        FirstWoman.reset();
        pc.reset();
    
        getch();
        return 0;
    }  
    

    或者这个:

    int _tmain(int argc, _TCHAR* argv[])
    {
        auto_ptr<Woman> FirstWoman(new Woman(NULL, 25, L"Anjelina"));
    
        auto_ptr<TMemoryStream> MStr(new TMemoryStream);
        auto_ptr<TStringStream> SStr(new TStringStream(L""));
    
        MStr->WriteComponent(FirstWoman.get());
        MStr->Position = 0;
        ObjectBinaryToText(MStr.get(), SStr.get());
        SStr->Position = 0;
        UnicodeString as = SStr->DataString;
    
        auto_ptr<TStringStream> pss(new TStringStream(as));
        auto_ptr<TMemoryStream> pms(new TMemoryStream);
    
        ObjectTextToBinary(pss.get(), pms.get());
        pms->Position = 0;
    
        auto_ptr<Woman> SecondWoman(new Woman(NULL));
        pms->ReadComponent(SecondWoman.get());
    
        cout << SecondWoman->Age << endl;
        cout << SecondWoman->Name.c_str() << endl;
    
        FirstWoman.reset();
        SecondWoman.reset();
    
        getch();
        return 0;
    }