Drawings SDK Developer Guide > Working with .dwg Files > Introduction > Basics of Database Operations and Database Objects > Working with Database Objects > Opening and Closing Database Objects
Opening and Releasing Database Objects

Before you can read a database object or modify it by working with its methods and properties, you must explicitly open the object for reading it or writing to it. You should also release it when the operation is completed.

Opening objects

Having a proper Object ID, you can open the object in a specific mode using the open function:


OdDbObjectPtr OdDbObjectId::safeOpenObject(OdDb::OpenMode openMode = OdDb::kForRead, bool openErasedOne = false) const;

You can open an object in one of three modes:

  • for reading
  • for reading and writing
  • for notifying

For example, to open a Block Table Record object by its ObjectID for writing:


OdDbBlockTableRecordPtr pBTR = btrId.safeOpenObject(OdDb::kForWrite);

After the object is opened, you can access its methods and properties by using the created smart pointer object:


pBTR->setName("NewBlock");
pBTR->appendOdDbEntity(pCircle);

Releasing objects

All objects implement smart pointer technology that is based on the reference counting mechanism and allows managing object lifecycles including deleting objects. That works differently for objects that belong to the database (resident objects) and objects that are not added to the database (non-resident objects).

Reference counter for objects is decreased when:

  • smart pointer goes out of scope
  • release() method is called
  • new value is assigned

For a non-database resident object, that means if the last smart pointer to the object goes out of scope or is assigned another value or the release() method is called, the reference counter gets a zero value and the object is destroyed.

For a database resident object, the database holds one reference to the object. So if the last smart pointer to the object goes out of scope, the reference counter decreases its value from 2 to 1 (last reference is held by the database) and the object is closed. And closed object is destroyed just after the database is destroyed.

For example:

{
  OdDbEntityPtr pLine = OdDbLine::createObject();
  OdDbDatabasePtr pDb = pHostApp->readFile();
  OdDbBlockTablePtr pTable  = pDb->getBlockTableId().safeOpenObject(OdDb::kForWrite);
  pLine = NULL;  // Line object is explicitly destroyed. This is equal to pLine.release(). 
  pTable = NULL; // Table object is closed. It will be destroyed after the Database is destroyed.
}  // Database is destroyed because pDb is out of scope and no pointers to it exist any more. 

 

Copyright © 2002 – 2021. Open Design Alliance. All rights reserved.