Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

Marshalling C++ Objects with XML


April 2002/Marshalling C++ Objects with XML

Listing 1: xmlbind.h
The main header file for XML Binding Technology

/*    Xmlbind.h

    This is a main header file for XML Binding Technology. The XML Binding is a method
    to convert C++ objects into XML text representation and vice versa.

    The idea of method is described below.

    Since C++ language has no means for an object to describe itself it is necessary 
    to explicitly define description table for each object type that you wish to 
    marshal. The object (or one of its parent) should be derived from Marshallable 
    interface and DECLARE_MARSHALING macro should be added into public section of the 
    class. Please refer to program examples to learn details of the XML Binding usage.

    Current implementation is using following assumptions for performance reasons:
    1. Maximum length of the XML representation of an object does not 
    exceed XML_DEFAULT_BUFSIZE (300K).
*/
#ifndef _XMLBIND_H_
#define _XMLBIND_H_

#include <windows.h>    // for data types definition

#pragma warning (disable:4786)
#include <sstream>
#include <string>
#include <list>
#include <map>
#include "crc32.h"

using namespace std;

#define ANY_ASP        (0xFFFFFFFF)

//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// G L O B A L   T Y P E S   R E G I S T R Y   D E F I N I T I O N

class XMLDoc;
class XMLElement;
class Marshallable;
class _ElementDescription;

//////////////////////////////////////////////////////////////////
// Elementary marshalling function pointer types
//////////////////////////////////////////////////////////////////
typedef void (*marshal_proc_t)(XMLDoc* pDoc, XMLElement* pElem, const 
_ElementDescription* pet, void* pdata, void* pother, int
aspect); typedef void (*unmarshal_proc_t)(void* obj, const _ElementDescription* pElem,
const char *ch, int length); ////////////////////////////////////////////////////////////////// // Instance handling function pointer type ////////////////////////////////////////////////////////////////// typedef Marshallable* (*_f_CreateInstance)(const char **atts, void *parent = 0); ////////////////////////////////////////////////////////////////// // // _Reg_TypeDescHelper // // Ancillary class used to keep a class description and other // information in a global registry. // ////////////////////////////////////////////////////////////////// class _Reg_TypeDescHelper { public: _Reg_TypeDescHelper() : m_ppElemDesc(0), m_procCreateInstance(0), m_signature(0) {} _Reg_TypeDescHelper(const _ElementDescription** arg_et, _f_CreateInstance
arg_CreateInstanceProc, const char* name) : m_ppElemDesc(arg_et), m_procCreateInstance(arg_CreateInstanceProc) { m_signature = CRC32().exec(name, strlen(name)); } const _ElementDescription** m_ppElemDesc; _f_CreateInstance m_procCreateInstance; DWORD m_signature; // 32-bit number that uniquely identifies the type }; ////////////////////////////////////////////////////////////////// // // _Reg_TypeNameToRefDescriptionMap // // Map type which maps a class name into the class description. // ////////////////////////////////////////////////////////////////// typedef map<string, _Reg_TypeDescHelper> _Reg_TypeNameToRefDescriptionMap; ////////////////////////////////////////////////////////////////// // // _Reg_GlobalTypesRegistry // // Singleton class that represents global types registry. // Due to this registry unmarshalling becomes possible. // ////////////////////////////////////////////////////////////////// class _Reg_GlobalTypesRegistry { public: static _Reg_TypeNameToRefDescriptionMap& Instance(); static void Destroy(); protected: _Reg_GlobalTypesRegistry(); private: static _Reg_TypeNameToRefDescriptionMap* inst; }; ////////////////////////////////////////////////////////////////// // // _Reg_Registrator // // Ancillary class used to register _Reg_TypeDescHelper of a praticular class // in the global registry. // ////////////////////////////////////////////////////////////////// class _Reg_Registrator { public: _Reg_Registrator(const char* name, const _ElementDescription** ppElemDesc,
_f_CreateInstance m_procCreateInstance) { _Reg_GlobalTypesRegistry::Instance()[name] = _Reg_TypeDescHelper(ppElemDesc,
m_procCreateInstance, name); } }; ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// // M A R S H A L L A B L E I N T E R F A C E D E F I N I T I O N ////////////////////////////////////////////////////////////////// // // _ElementDescription // // Ancillary class used to describe a class data member. // ////////////////////////////////////////////////////////////////// class _ElementDescription { public: WORD offset; // offset in bytes to the data field WORD size; // size in bytes of the data field char *field_name; // field name unsigned field_name_len; // field name length (for better marshalling performance) marshal_proc_t marshal; unmarshal_proc_t unmarshal; int count; // equals to 1 for single elements; used to support arrays of elements int aspect; // either ANY_ASP (for any aspect) or aspect mask int attrib; // 0-simple data, 1-attribute, 2-complex data _ElementDescription(const char* arg_info, int arg_attrib, WORD arg_offset,
WORD arg_size, int arg_count, char *arg_field_name,
marshal_proc_t marshal_proc, unmarshal_proc_t unmarshal_proc,
int arg_asp) : offset(arg_offset), size(arg_size), count(arg_count),
field_name(arg_field_name), marshal(marshal_proc),
unmarshal(unmarshal_proc), attrib(arg_attrib), aspect(arg_asp) { field_name_len = strlen(field_name); } }; ////////////////////////////////////////////////////////////////// // // _RefToElementDescription // // Ancillary class used to link to ElementDescription array // of the marshallable class and to link to the base class if any. // ////////////////////////////////////////////////////////////////// struct _RefToElementDescription { const _RefToElementDescription* m_pBaseElemDesc; _ElementDescription** m_ppElemDesc; }; ////////////////////////////////////////////////////////////////// // // Marshallable // // Abstract base class used as a parent to a C++ class. // ////////////////////////////////////////////////////////////////// class Marshallable { public: // Constructors/destructors virtual int Marshal(XMLDoc*& pDoc, const void* other = 0, XMLElement*
pDocElem = 0, int aspect = ANY_ASP); virtual ~Marshallable() {} // Abstract interface functions virtual const _RefToElementDescription* GetElementsTable() = 0; virtual const char* GetTypeName(int aspect = ANY_ASP) const = 0; virtual DWORD GetTypeId(int aspect = ANY_ASP) const = 0; }; ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// // C O R E M A C R O S D E F I N I T I O N #define DECLARE_MARSHALING(type_name) \ static Marshallable* CreateInstance(const char **atts, void *parent = 0); \ virtual DWORD GetTypeId(int aspect = ANY_ASP) const \ { \ map<int, string>::const_iterator it = (*_sm_pAspectMap).find(aspect); \ if(it == (*_sm_pAspectMap).end()) \ return 0; \ \ _Reg_TypeNameToRefDescriptionMap::const_iterator it2 =
_Reg_GlobalTypesRegistry::Instance().find((*it).second); \ \ if(it2 != _Reg_GlobalTypesRegistry::Instance().end()) \ { \ const _Reg_TypeDescHelper& th = (*it2).second; \ return th.m_signature; \ } \ return 0; /* not found */ \ } \ \ virtual const char* GetTypeName(int aspect = ANY_ASP) const \ { \ map<int, string>::const_iterator it = (*_sm_pAspectMap).find(aspect); \ return (it == (*_sm_pAspectMap).end()) ? "unknown" : (*it).second.c_str(); \ } \ \ virtual const _RefToElementDescription* GetElementsTable() \ { \ return &_sm_refToElemDesc; \ } \ \ /* Static data members for ancillary use */ \ static _ElementDescription* _sm_ElementsDescriptionTbl[]; \ static _RefToElementDescription _sm_refToElemDesc; \ static map<int, string>* _sm_pAspectMap; \ \ static map<int, string>* getAspectMap() \ { \ if(0 == _sm_pAspectMap) \ _sm_pAspectMap = new map<int, string>; \ \ return _sm_pAspectMap; \ } #define BEGIN_IMPLEMENT_MARSHALING(class_name) \ IMPLEMENT_ASPECT(class_name, ANY_ASP, #class_name) \ static _Reg_Registrator _r_##class_name (#class_name, (const _ElementDescription**)
&(class_name::_sm_ElementsDescriptionTbl[0]), (_f_CreateInstance)
class_name::CreateInstance);\ map<int, string>* class_name::_sm_pAspectMap = 0; \ _RefToElementDescription class_name::_sm_refToElemDesc = { 0,
&class_name::_sm_ElementsDescriptionTbl[0] }; \ _ElementDescription* class_name::_sm_ElementsDescriptionTbl[] = { #define BEGIN_IMPLEMENT_MARSHALING2(class_name, base_class) \ IMPLEMENT_ASPECT(class_name, ANY_ASP, #class_name) \ static _Reg_Registrator _r_##class_name (#class_name, (const _ElementDescription**) &(class_name::_sm_ElementsDescriptionTbl[0]), (_f_CreateInstance)
class_name::CreateInstance);\ map<int, string>* class_name::_sm_pAspectMap = 0; \ _RefToElementDescription class_name::_sm_refToElemDesc = {
&base_class::_sm_refToElemDesc, &class_name::_sm_ElementsDescriptionTbl[0] }; \ _ElementDescription* class_name::_sm_ElementsDescriptionTbl[] = { #define IMPLEMENT_ASPECT(class_name, asp, fnm) static bool class_name##asp =
((*class_name::getAspectMap())[asp] = fnm, false); #define XDAT(type,field,fnm) new _ElementDescription(#type, 0,
((int)&(((_alias*)0)-> field)), sizeof(type), 1,
fnm, marshal_##type, unmarshal_##type, ANY_ASP), #define XATR(type,field,fnm) new _ElementDescription(#type, 1,
((int)&(((_alias*)0)-> field)), sizeof(type), 1,
fnm, marshal_##type, unmarshal_##type, ANY_ASP), #define XCUSTOM(type,field,fnm) new _ElementDescription(#type, 2,
((int)&(((_alias*)0)-> field)),
sizeof(((_alias*)0)-> field), 1, fnm,
marshal_##type, 0, ANY_ASP), #define XASP(type,field,fnm,asp) new _ElementDescription(#type, 0,
((int)&(((_alias*)0)-> field)), sizeof(type), 1,
fnm, marshal_##type, unmarshal_##type, asp), // array of elementary variables (e.g. char[], int[], float[], string[]) #define XARR(type,size,field,fnm) new _ElementDescription(#type, 4,
((int)&(((_alias*)0)-> field)), sizeof(type),
size, fnm, marshal_##type, unmarshal_##type,
ANY_ASP), #define END_IMPLEMENT_MARSHALING() 0, (_ElementDescription*) _alias ::getAspectMap() }; ////////////////////////////////////////////////////////////////// // // _XMLObject // ////////////////////////////////////////////////////////////////// class _XMLObject { public: const _RefToElementDescription& typmap; void* obj; const _ElementDescription* field; // current field pointer; used when
// parsing an element _XMLObject(const _RefToElementDescription* arg_typmap, void* arg_obj) :
typmap(*arg_typmap), obj(arg_obj), field(0) {} const _ElementDescription* FindField(const char *name) const; }; ////////////////////////////////////////////////////////////////// // Marshaling utilities for basic types ////////////////////////////////////////////////////////////////// void marshal_int(XMLDoc* pDoc, XMLElement* pElem, const _ElementDescription* pet,
void* pdata, void* pother, int aspect); void marshal_bool(XMLDoc* pDoc, XMLElement* pElem, const _ElementDescription* pet,
void* pdata, void* pother, int aspect); void marshal_char(XMLDoc* pDoc, XMLElement* pElem, const _ElementDescription* pet,
void* pdata, void* pother, int aspect); void marshal_float(XMLDoc* pDoc, XMLElement* pElem, const _ElementDescription* pet,
void* pdata, void* pother, int aspect); void marshal_double(XMLDoc* pDoc, XMLElement* pElem, const _ElementDescription* pet,
void* pdata, void* pother, int aspect); void marshal_pchar(XMLDoc* pDoc, XMLElement* pElem, const _ElementDescription* pet,
void* pdata, void* pother, int aspect); void marshal_BYTE(XMLDoc* pDoc, XMLElement* pElem, const _ElementDescription* pet,
void* pdata, void* pother, int aspect); void marshal_WORD(XMLDoc* pDoc, XMLElement* pElem, const _ElementDescription* pet,
void* pdata, void* pother, int aspect); void marshal_string(XMLDoc* pDoc, XMLElement* pElem, const _ElementDescription* pet,
void* pdata, void* pother, int aspect); void unmarshal_int(void* obj, const _ElementDescription* pElem, const char *ch, int length); void unmarshal_bool(void* obj, const _ElementDescription* pElem, const char *ch, int length); void unmarshal_char(void* obj, const _ElementDescription* pElem, const char *ch, int length); void unmarshal_float(void* obj, const _ElementDescription* pElem, const char *ch, int length); void unmarshal_double(void* obj, const _ElementDescription* pElem, const char *ch, int length); void unmarshal_pchar(void* obj, const _ElementDescription* pElem, const char *ch, int length); void unmarshal_BYTE(void* obj, const _ElementDescription* pElem, const char *ch, int length); void unmarshal_WORD(void* obj, const _ElementDescription* pElem, const char *ch, int length); void unmarshal_string(void* obj, const _ElementDescription* pElem, const char *ch, int length); ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// // O T H E R M A R S H A L L I N G H E L P E R C L A S S E S ////////////////////////////////////////////////////////////////// // // XMLElement // ////////////////////////////////////////////////////////////////// class XMLElement { friend class XMLDoc; public: XMLElement(){} ~XMLElement(); int setAttribute(const char* attr_name, unsigned nAtrLen, const char* value,
unsigned nValLen); XMLElement* appendElement(const char* pszTag, unsigned nTagLen, const char*
pszText = 0, unsigned nTextLen = 0); void* operator new(size_t stBlock, XMLDoc* pOwner, XMLElement* pParent, int
nBegOfs, int nTagLen); void operator delete(void*); static char m_Storage[5000]; // contains temporary XML Elements. protected: XMLDoc* m_pOwner; // owner document XMLElement* m_pParent; // parent element if any int m_nBegOfs; // beginning of the element int m_nAtrOfs; // end of the attributes int m_nTagLen; // tag length static char* m_Ptr; // pointer to last temporary XML Element content }; ////////////////////////////////////////////////////////////////// // // XMLDoc // ////////////////////////////////////////////////////////////////// class XMLDoc { friend class XMLElement; public: enum { XML_DEFAULT_BUFSIZE = 300*1024 }; XMLDoc(const char* szType); virtual ~XMLDoc(); XMLElement* getDocumentElement() { return &m_RootElem; } const char* ReleaseText(); protected: string m_sType; // root element name char *m_szBuf; // beginning of the intenal buffer unsigned m_nBufSize; // size of the internal buffer char *m_szPtr; // pointer where to insert new elements unsigned m_nTail; // length of the tail with useful data bool m_bReleased; // true if the content of the document was released XMLElement m_RootElem; // root element static char m_MainBuf[XML_DEFAULT_BUFSIZE]; // output of marshaling will be
// stored in the buffer inline void m_SetOpenTag(const char* pszTag, int nTagLen, bool bNewLine = false) { *m_szPtr++ = '<'; while(--nTagLen >= 0) { *m_szPtr++ = *pszTag++; } *m_szPtr++ = '>'; if(bNewLine) *m_szPtr++ = '\n'; } inline void m_SetCloseTag(const char* pszTag, int nTagLen) { *m_szPtr++ = '<'; *m_szPtr++ = '/'; while(--nTagLen >= 0) { *m_szPtr++ = *pszTag++; } *m_szPtr++ = '>'; *m_szPtr++ = '\n'; } inline void m_SetText(const char* pszText, int nTextLen) { while(--nTextLen >= 0) { *m_szPtr++ = *pszText++; } } inline void m_SetAttribute(const char* attr_name, const char* value) { *m_szPtr++ = ' '; while(*attr_name != 0) { *m_szPtr++ = *attr_name++; } *m_szPtr++ = '='; *m_szPtr++ = '"'; while(*value != 0) { *m_szPtr++ = *value++; } *m_szPtr++ = '"'; } inline void m_PlaceText(const char* pszText, int nTextLen) { char* szPtr = m_szPtr; while(--nTextLen >= 0) { *szPtr++ = *pszText++; } } inline void m_GetSpace(int nSpace) { // move tail if necessary if(m_nTail != 0) { memmove(m_szPtr+nSpace, m_szPtr, m_nTail); } } }; #endif


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.