CppUtils‎ > ‎

Documentation

Overview

This document describes introduction and available functionality with CppUtils library. CppUtils Library is auxiliary utility library for C++ for very popular Boost library ( http://www.boost.org). This library adds additional functionality or another implementation for Boost.

CppUtils functionality

This manual is only introduction to functionality library. For more details look at the API docs.

Common classes

RefObject

RefObject is the base class for all reference counting objects. RefObject supports boost::intrusive_ptr<>, debug tracing and scope guard. RefObject based upon fast boost::detail::atomic_count.

SystemException

SystemException provides standard interface for all system exception and support for some OS system backtrace functionality.

Dynamic modules ( DLL/SO/DYLIB ) loading support (DynMod API)

DynMod API provides access to ModulesFactory class and IModule interface. You can load your external library as plugin your system with ModulesFactory. For example:

//Loading your dynamic library
IModule::SharedPtr module = ModulesFactory::getInstance()->loadModule("TestDynmod", cpputils::Version(YOUR_API_COMPILED_VERSION_DEFINE));

// Creating object instance for your own API (ITestInstance)
boost::shared_ptr<ITestInstance> instance = module->createModuleObject<ITestInstance>();

// Access to any your members
instance->doIt();

Your module is the simple dynamic library (DLL/SO/DYLIB) with some special methods. Look at example for libTestDynmod.dll code:

// Your standard Windows DLL export/import define
#ifndef TESTDM_DLLPRFX
        #ifdef WIN32
                #ifdef TESTDYNMOD_EXPORTS
                        #define TESTDM_DLLPRFX __declspec(dllexport)
                #else
                        #define TESTDM_DLLPRFX __declspec(dllimport)
                #endif
        #else
                #define TESTDM_DLLPRFX
        #endif
#endif


/**
 * Initialization module library function
 */
DYNMOD_INIT_FUNC(TESTDM_DLLPRFX) {
        // Macros DYNMOD_INIT_FUNC defines the signature for C method with parameter oVersion where you can obtain the 
        // API version from application
        const Version oModCompiledVersion(YOUR_API_COMPILED_VERSION_DEFINE);

        // You can check your API compatibility here
        if(oVersion.getMajorVer()!=oModCompiledVersion.getMajorVer())
                return ACTIVATE_TRANSPORT_MODULE_INCORRECT_API;

        return ACTIVATE_TRANSPORT_MODULE_SUCCESS;
}

/**
 * Unloading library function without parameters
 */
DYNMOD_FINALIZE_FUNC(TESTDM_DLLPRFX) {
        // std::cout << "Test dynmod finalized successfully" <<std::endl;
}

/**
 * Factory method for creation user objects (The method provides access to your C++ API)
 */
DYNMOD_CREATEINSTANCE_FUNC(TESTDM_DLLPRFX) {
        return new TestInstanceImpl();
}


void TestInstanceImpl::doIt() {
        // std::cout << "TestInstance " << this << " doIt are called!" <<std::endl;
}

Operation System and Platform Abstraction Support Functions

Auxiliary functions provides access to some OS functionality available with OSTools and OSEndianTools classes. With OSTools you can spawn with asynchronous manner external processes and obtain access to High Resolution Timers (if OS support available). OSEndianTools is abstraction for BigEndian to LittleEndian conversation functions for integer and numeric data types.

Effective Programming Templates (EPT)

Thread pool

Thread pools

ThreadPool class creates threads with the specified maximum and initial count. You can schedule your task on thread pool with ThreadPool.schedule method. Also you can schedule your task with assigned task id if you want take more control for task lifecycle (canceling task by id, wait to finish, etc) and don't want run tasks simultaneously for same id. For example:

// Creating a thread pool. Maximum count of threads in the pool is 10 and initially will be created is 3

ThreadPool* pool = new ThreadPool ( 10 , 3 );

// Creation task id
ThreadPool::TaskId myTaskId = pool->createTaskId();
// Scheduling the user task function in user class (boost::bind usage)

// All scheduled tasks per task id can't run simultaneously
pool->schedule (
  myTaskId,
  boost::bind ( &MyClass::myTaskHandler, this)
);

// Canceling all scheduled jobs by id
pool->cancel ( myTaskId );

// Wait for finish scheduled jobs by id
pool->wait ( myTaskId );

Object pools

You can utilize your objects with object instances pooling in the heap. ObjectPool class provides access to simple pooling. Look at the sample:

// Create a new object pool. Maximum pool size is 1000, initial created 5
ObjectPool<MyClass> pool = new ObjectPool<MyClass> ( 1000, 5 );

// Get an instance from the pool
MyClass* instance = pool->getObject();

// Return the instance to the pool
pool->returnObject(instance);

Timers (Timer queue)

Timer provides timer queue and based upon OS high-resolution timer API. With the timer you can schedule your task for the spefied time interval.

For example:

// Create your timer
Timer* myTimer = new Timer();

// Assign your own id for this timer event
Timer::TimerId myTimerId = 1;

// Schedule one timer event
myTimer->schedule(
  myTimerId,
  10000, // Handler must be called after 10 sec
  boost::bind(&MyClass::myTimerHandler, this)
);

Extended data types

Subroutines provides access to useful but not available in C++ or Boost data types.

BigInteger

BigInteger can store very big integers (like Java BigInteger). You can initialize this type with standard std::string, int, long, double datatypes, call arithmetic operations or use logical operators. For example:

BigInteger a(10L), b("20000000000000000000000");

if ( a < b) {
   a*= b / BigInteger(1000000);
}

BigDecimal

BigDecimal stores very big fixed point numbers (like Java BigDecimal) . You can initialize this type with standard std::string, int, long, double datatypes, call arithmetic operations or use logical operators. Also you can use this format for store financial prices and costs because this type based up on fixed point arithmetic. For example:

BigDecimal a("0.5"), b(1);

if ( a < b) {
   a+= BigDecimal("1.5");
}

Input/Output routines

If you working too much with raw byte arrays, these functions provide access to helper classes for efficient manage and store your data.

ByteBuffer

ByteBuffer is a wrapper class for byte arrays ( unsigned char[] ) with length and read/write positions and very useful additional functions like append, fill, replace, cut, seek, etc. For example:

// Creating a byte buffer with initial capacity 1024 bytes
ByteBuffer* myBuffer = new ByteBuffer( 1024 );

// Appending a C-style buffer
const unsigned char cStyleBuffer[] =  { 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F };
myBuffer->append (cStyleBuffer, sizeof ( cStyleBuffer ) );

// Appending another ByteBuffer
myBuffer->append ( anotherBuffer );

// Get len of the buffer
myBuffer->getLen();

// Capacity of buffer
myBuffer->getCapacity();

// Resizing without lost current data
myBuffer->setLen ( 2048 );

// Filling the buffer with 0
myBuffer->fill ( 0 );

ByteArrayInputOutputStream

ByteArrayInputOutputStream provides implementation based upon ByteBuffer where you can write buffers to the stream and read from the stream in parallel threads with low thread locking algorithm based on blocks of arrays.

Building CppUtils library from the source code

Required 3rdparty libraries

  • Boost C++ library (http://www.boost.org)

  • GNU MP Library (http://gmplib.org/) or MPIR fork for Windows (http://www.mpir.org)

Building the source files on Unix-like OS (Linux, Solaris, Mac OS, Cygwin)

Build or install all thirdparty libraries. For Ubuntu you can use very simple apt-get tool to receive and install all required libraries.

Use configure script in the <project-dir>/workspaces/autotools. If you build Boost library names with additional gcc platform information (e.g. libboost-gcc44.so) use --with-boostpostfix option for configure script. For example:

# ./configure 
     --with-cppflags="-I../../../../../3rdparty/boost/include" 
     --with-ldflags="-L../../../../../3rdparty/boost/libs"
     --with-boostpostfix=gcc44

Building the source files on Windows OS

Just open Visual Studio project file in <project-dir>/workspaces/msvc10 directory and configure include paths to additional libraries