CArchive使用的一种错误方式

http://www.codeproject.com/Articles/1115/The-Right-Way-To-Do-Object-Serialization

Introduction介绍

Object serialization is one of the most powerful features of MFC. 对象串行化是MFC的一个重要特性。With it you can store your objects into a file and let MFC recreate your objects from that file.利用它你可以将你的对象存入一个文件,然后让MFC通过读取文件去重新创建它们。 Unfortunately there are some pitfalls in using it correctly.不幸的是,这里面有很多的陷阱。 So it happened that yesterday I spent a lot of time in understanding what I did wrong while programming a routine that wrapped up some objects for a drag and drop operation. 昨天我花了很长的时候去查清一个实现拖放操作时出现的BUG,After a long debugging session I understood what happened and so I think that it might be a good idea to share my newly acquired knowledge with you.我花了很长的时间才调试出来,所以我觉得有必要和大家分享一下。

The Wrong Way错误的方式

Let's start with my wrong implementation of object serialization.先说我的错误的方式。 A very convenient way to implement drag and drop and clipboard operations is to wrap up your objects in a COleDataSource object. 一个实现拖放操作非常方便的方式是把你的对象封装到一个COleDataSource对象里。This object can hold any data with a defined format or with a format that you can define and then it can be passed either to the clipboard by calling COleDataSource::SetClipboard or to the drag and drop handler by callingCOleDataSource::DoDragDrop.这样这个对象可以存储下系统已经定义或者由你定义的格式的任何数据,然后它可以通过调用 COleDataSource::SetClipboard 传递给剪贴板,或者通过调用COleDataSource::DoDragDrop 传递给拖放操作处理函数。

If you want to transfer a set of known objects between different parts of your applications, it is convenient to serialize them in a memory file and to wrap them up in a COleDataSource.如果你想将一些已知的对象传到你的应用程序的不同部分,将它们串行到内存文件(memory file)然后将它们封装到一个COleDataSource里面是一种好办法

Let's start: This is my object:

让我们开始:这是我的对象:

 Collapse | Copy Code

class CLeopoldoOb : public CObject

{

    DECLARE_SERIAL(CLeopoldoOb)

// construction/destruction

public:

    CLeopoldoOb();

    // ....

protected:

    // some data....

    // some methods...

};

And this is my first version of the routine that wrapped up a set of those objects in the COleDataSource:

这是第一个版本中我将这些对象封装到COleDataSource的方式:

 Collapse | Copy Code

...

COleDataSource* pDataSource = new COleDataSource;

if ( !pDataSource ) {

    return NULL;

}

// this is the memory file...

CSharedFile sf (GMEM_MOVEABLE|GMEM_DDESHARE|GMEM_ZEROINIT);

// this archive works on the memory file

CArchive    ar (&sf, CArchive::store);

// serialize the quantity

ar << m_nObjectCount;

for ( int i = 0; i < m_nObjectCount; i++ ) {

    CLeopoldoOb  leo;

    // now prepare the contents of the leopoldo object

    ...

    // object contains all data we need

    // serialize the object

    ar << &leo

}

ar.Flush ();

ar.Close ();

pDataSource->CacheGlobalData (g_cfLeopoldo, sf.Detach ());

pDataSource->DoDragDrop ();

if ( pDataSource->m_dwRef <= 1 ) {

    delete pDataSource;

}

else {

    pDataSource->ExternalRelease (); // !!!

}

...

And let's see the routine that unwraps the objects when they are dropped:

让我们看看当它们被放置时,解除封装的方法:

 Collapse | Copy Code

...

BOOL CMainFrame::OnDrop (COleDataObject* pDataObject, 

    DROPEFFECT dropEffect, CPoint point)

{

    if ( pDataObject->IsDataAvailable (g_cfLeopoldo) ) {

        CLeopoldoOb     *pOb;

        HGLOBAL         hMem = pDataObject->GetGlobalData (g_cfLeopoldo);

        CMemFile        mf;

        UINT            nCount;

        mf.Attach ((BYTE *)::GlobalLock (hMem), ::GlobalSize (hMem));

        CArchive ar (&mf, CArchive::load);

        // get the object count

        ar >> nCount;

        for ( UINT n = 0; n < nCount; n++ ) {

            try {

                // create the object out of the archive

                ar >> pOb;

                // now do what you have to do with the object

                ....

                // we do not need it any more...

                delete pOb;

            }

            catch { CException *pEx ) {

                // do some error handling

                pEx->Delete ();

            }

        }

        ar.Close ();

        mf.Detach ();

        ::GlobalUnlock (hMem);

        ::GlobalFree (hMem);

        return nCount > 0;

    }

    return FALSE;

}

What happened? 后面发生了什么呢?Apparently this stuff worked, if you had only one object wrapped up. 非常明显,上面的代码发挥了作用,当你只有一个对象时。OK. Sometimes the application crashed but basically it worked. 但是,有的时候程序会崩溃,但多数情况下它可以正常工作。If instead more than one object was wrapped up, two strange things happened:如果多于一个对象要被封装时,两件奇怪的事情会发生

· Only the first object was unwrapped只有第一个对象被解除封装

· A CArchiveException with badIndex sometimes occurred一个带有badIndex 信息的CArchiveException 被抛出

When tested under the debugger, I saw that the creation of the object from the serialization failed starting from the second time.当我在调试器下调试时,我发现当创建对象的操作在被第二次被调用的时候就开始失败了。 Since there was definitively no error in the load routine, I reached the conclusion that the archive data must be messed up.虽然在文件载入的方式上绝对没有错误,我得出一个结论——串行化数据肯定被损坏了。

What Went Wrong?到底出了什么问题?

After debugging in the profundities of CArchive I discovered that the process of storing dynamic objects is not as simple as I imagined it should be.通过深入的调试,我发现动态对象的串行化不是像我想象中的那么简单。

Obviously my error was during the creation of the archive. 非常明显,我的错误出在archive对象的创建过程中。There are two important rules:有两条非常重要的规则:

1 The objects must be dynamically created (with CRuntimeClass::CreateObject).对象应该被动态创建(使用CRuntimeClass::CreateObject

2 The objects must remain valid until the serialization has been finished.对象在串行化过程完成之前,应当一直处于有效状态(不能被销毁)

If you are asking why, take a look into the source of CArchive and you will see that the archive stores additional information about those objects during its life.如果你要问为什么,请看看CArchiver的源代码,然后你会发现在生存域之内archive存储了关于对象的额外信息。 Furthermore the entire MFC seems to have knowledge about all dynamically created CObjects.更进一步地说,整个MFC似乎存储了所有关于动态创建的CObject对象的信息。

The Right Way正确的方式

First of all we need a little helper class that will make life simpler:

 Collapse | Copy Code

class CAllocatedObArray : public CObArray

{

public:

    CAllocatedObArray           () { }

    virtual ~CAllocatedObArray  () { RemoveAll (); }

public:

    void  RemoveAll ();

};

void CAllocatedObArray::RemoveAll ()

{

    for ( int i = 0; i < GetSize (); i++ ) {

        CObject *pObject = GetAt (i);

        if ( pObject ) {

            delete pObject;

        }

    }

}

The following is the modified wrapper routine.这是已经修改了的封装方法。 You will see that all objects are created dynamically and stored into this array.你会发现所有对象都被动态创建后,然后存入了这个数组(Array)中。 After the serialization has finished, the array goes out of scope and our allocated objects will be automatically be destroyed.当串行化完成后,这个数组走出了生存域,然后对象会被自动销毁掉。

 Collapse | Copy Code

...

COleDataSource* pDataSource = new COleDataSource;

if ( !pDataSource ) {

    return NULL;

}

// this is the memory file...

CSharedFile         sf (GMEM_MOVEABLE|GMEM_DDESHARE|GMEM_ZEROINIT);

// this archive works on the memory file

CArchive            ar (&sf, CArchive::store);

// this array holds our objects

CAllocatedObArray   tmpArray;

// This is needed to access the runtime class

CLeopoldoOb         leo;

// serialize the quantity

ar << m_nObjectCount;

for ( int i = 0; i < m_nObjectCount; i++ ) {

    CLeopoldoOb *pLeo = (CLeopoldoOb *) leo.GetRuntimeClass ()->CreateObject ();

    // store it in the array

    tmpArr.Add (pLeo);

    // now prepare the contents of the leopoldo object

    ...

    // object contains all data we need

    // serialize the object

    ar << pLeo

}

ar.Flush ();

ar.Close ();

pDataSource->CacheGlobalData (g_cfLeopoldo, sf.Detach ());

pDataSource->DoDragDrop ();

if ( pDataSource->m_dwRef <= 1 ) {

    delete pDataSource;

}

else {

    pDataSource->ExternalRelease (); // !!!

}

...

This works. 这是有效的。Probably this will be nothing new for all experts among you, but since I did make this error after years of programming MFC, I hope that this article will help some beginner.对于你们中精通这个的人,很可能这并不是什么新的概念,但是因为我虽然有多年MFC经验但在这里仍然犯了错误,我希望这篇文章对初学者会有所帮助。

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值