Thomas Sampson


Leave a comment

CallOnce

UPDATE: Modified the implementation to use singleton method access to CallOnce function map. Also added example of usage distributed across multiple source files.

CallOnce is a C++ technique I have picked up recently which allows code to be executed (usually to perform static initialisation or other housekeeping activities) before the program entry point (usually main). Rather than having some Init() method right at the beginning of the application which attempts to initialise all your static objects and data, the CallOnce mechanism allows each cpp file to register it’s own functions which gets called during global static initialisation (before the program entry point). This system is much cleaner and easier to manage, removing the requirement for a large central “Init()” function.

CallOnce can be implemented in various ways. In C++ global static initialisation order is undefined, for this reason additional levels of control can be added to the CallOnce implementation to define the order in which the registered functions get called (very important if there are dependencies between static objects and data). In this post I will keep things as simple as possible and use a couple of examples to demonstrate this technique.

Example 1

In this simple example a class “CallOnce” has a constructor which takes a function pointer (return type void, no parameters). In the constructor of the CallOnce class the function passed in gets called.
To use this system all that is required is to create some global instance of the CallOnce object and pass it the address of an initialisation function (in this case ::Init). The output proves that the Init function was in fact called before the program reached main.

Main.cpp

#include <stdio.h>

class CallOnce
{
	public:
		typedef void (*CallOnceFunc)(void);
		explicit CallOnce(CallOnceFunc func)
		{ func(); }
};

void Init()
{
	printf("Hello ");
}

const CallOnce gCallOnce( &Init);
int main(int argc, char* argv[])
{
	printf("World");
	return 0;
}

Output


> Hello World

Example 2

In this slightly more involved example, rather than immediately calling the function passed in the constructor, the function is inserted into a static map and stored there until CallOnce::Init() is called. When this happens, all of the registered functions get called in order of their priority (as std::map is automatically ordered by key and we store the priority value as the map key). By default all registering functions are given priority 1000 unless the overloaded constructor is used to specify a priority (in this system 0 = Highest priority). In the example shown below, even though Init1 is registered before Init2, due to the priorities specified they are executed in reverse order.

NOTE: The CallOnce instances do not all have to exist right before main, they can be scattered around your code base inside any cpp file you want.

CallOnce.h

#include <stdio.h>
#include <map>

class CallOnce
{
	public:
		typedef void (*CallOnceFunc)(void);
		typedef std::map<int, CallOnceFunc> FuncMap;

		explicit CallOnce(CallOnceFunc func)
		{
			static const unsigned int uDefaultPriority = 1000;
			GetFuncMap().insert(std::make_pair<int,CallOnceFunc>(uDefaultPriority, func));
		}
		explicit CallOnce(CallOnceFunc func, int iPriority)
		{
			GetFuncMap().insert(std::make_pair<int,CallOnceFunc>(iPriority, func));
		}
		static void Init()
		{
			FuncMap::const_iterator it(GetFuncMap().begin());
			for(; it != GetFuncMap().end(); ++it)
				(*it).second();
		}
	private:
		static FuncMap& GetFuncMap()
		{
			static FuncMap singleton;
			return singleton;
		}
};

Foo.cpp

#include "CallOnce.h"

void Init1() { printf("Init1 Called\r\n"); }
const CallOnce gCallOnce	 ( &Init1, 1);

Bar.cpp

#include "CallOnce.h"

void Init2() { printf("Init2 Called\r\n"); }
const CallOnce gCallOnceAgain( &Init2, 0);

Main.cpp

#include "CallOnce.h"

int main(int argc, char* argv[])
{
	CallOnce::Init();
	printf("Main Called");
	return 0;
}

Output


> Init2 Called

> Init1 Called

> Main Called

Advertisements


Leave a comment

Visual Studio Post Build Events

I am currently working on a Visual Studio solution that has multiple projects each building an exe or library to a different directory. My aim was to copy some of the output files all into the same folder as the main application is dependent on the other projects residing in the same directory.

Previously, if I had updated and rebuilt one of the projects in the solution I would manually locate the output file and drag it into the right place. However today I discovered the post build events area in Visual studio (right click solution > Build events). Here you can input your own DOS commands and utilise a bunch of VS environmental macros/variables to create a simple batch script which is automatically executed every time you build/rebuild your solution. Any output from your DOS commands (echo) is printed into the ouput window inline with all the other build information Visual Studio provides during the build process.

Here is a simple example which solved my problem but there are much more advanced techniques you could use with this feature.

echo Copying pre loader application to build directory
copy "$(SolutionDir)cwpl_app\bin\Debug\CwplApp.exe" "$(OutDir)"
echo Launching pre loader tool
"$(SolutionDir)cwpl_app\bin\Debug\CwplApp.exe"


Understanding the virtual keyword in C++

The virtual keyword is used to allow for true polymorphism to take place in your c++ application.

A real world example

Let’s create a situation which requires both a base and specialised (derived) class architecture. We will use the real world example of Transport and Car, where Car is derived from transport (as would be a bike, or a plane for that matter). Here are the defenitions for each object

The Transport Object

class Transport

{

     private:

        int topSpeed;

     public:

        void IdentifyMyself()

        {
             cout << "I am a Transport Object";
        }

};

The Car Object

class Car : public Transport

{

     private:

     public:

     void IdentifyMyself()

     {

          cout << "I am a Car Object" ;

     }

};

Simple enough?

So, lets examine what actually goes on here

1. The Transport class is created as our base class.

2. The Transport class has one private data member.

3. The Transport class has one public method named IdentifyMyself() which outputs a message.

4. The Car object is created as our specialised/derived class.

5. The Car publicly inherits from the base class Transport, obtaining its private data member topSpeed.

6. The Car also defines a public method named IdentifyMyself() which also outputs a message.

What next?

The important part to take from above is that Car inherits from Transport, and that they both contain a defenition for the method IdentifyMyself().

So let’s use our objects! Here is a snippet of code which uses our objects and their methods…

Transport t;

Car c;

t.IdentifyMyself();

c.IdentifyMyself();

Output

I am a Transport ObjectI am a Car object

So, the Car’s method overrides the base class method and the two objects print a different message, simple. Now consider the following….

Test code

Transport* t

Car c;

t=&c;

c.IdentifyMyself();

t->IdentifyMyself();

We now have a car object as before, but this time we setup a pointer “t” (of the type Transport) to point to our Car, “c” . We are allowed to do so as “Car is a type of Transport”. However, take note of the output.

Output

I am a Car objectI am a Transport object

Even though our pointer “t” points to a Car object, we still call the IdentifyMyself() method of the base class. This is because there is no overriding, and as the pointer is of the type Transport, we simply call the Transport’s method, no longer the one overridden by Car. This is where the virtual keyword comes into play.

Let’s redefine the base class Transport to unclude a virtual method…

The New Transport Object

class Transport

{

     private:

        int topSpeed;

     public:

        virtual void IdentifyMyself()

        {
             cout << "I am a Transport Object";
        }

};

Now lets run the same code again and notice the difference in output….

Test code

Transport* t

Car c;

t=&c;

c.IdentifyMyself();

t->IdentifyMyself();

Output

I am a Car objectI am a Car object

This time when we dereference the pointer “t”,  even though our pointer is of the type Transport, due to Transport using the virtual keyword before IdentifyMyself(), it now forces the program to downcast to our inherited object Car and call the overridden IdentifyMyself() method instead.

How does this work under the hood?

Let’s think back to when our Transport class  did not employ the virtual keyword. At compile time we can collect up all Transport’s class methods and know where they will reside in memory. However, when we use the virtual keyword, when accessing a pointer to a Transport object, these methods could be anywhere in memory (depending upon the layout of the derived type which overrides them).

The way to resolve this is for each object which uses virtual methods, to keep a vtable (virtual method lookup table) which keeps a list of virtual function pointers. This vtable is always kept at memory offset 0 and can be though of as a hidden datamember for classes which use the virtual keyword or override virtual methods. This can be seen when watching a pointer to our Transport instance, using the Visual Studio Debugger as shown below as __vfptr (virtual function pointers).

This is done automatically by the compiler for any base class which employ virtual methods, and inherently for those that derive from the base class. This vtable is always kept at memory offset 0, so we can always take a pointer to a Transport object, and check its vtable and call the right method. This becomes more complex with multiple inheritence.

Summary

Imagine increasing the scale of this program to include Planes, Trains and Motorbikes. We could now keep a list, 100 items long, of transport pointers…

Transport* mylist[100];

…and iterate through this list, calling ->IdentifyMyself() on each item. Now that the base class implements the virtual keyword, true polymorphism takes place and any derived classes which choose to override this method, get their chance to output a custom message. For those classes that dont override the IdentifyMyself() method, the base class method will be called.


Using a QueryPerformanceTimer in C++

“Query Performance Counters” can be used to create timers within your code, usually used to capture the time it takes to carry out a given function or set of instructions. Query Performance Counters can be particularly useful when you are looking to optimise a piece of code and need to run comparisons on your optimisations.

To start using performance timers first make sure to include the following..

#include <windows.h>
#include “stdio.h”

using namespace std;

Next you need to create some variables to hold the timing data, these are of the type LARGE_INTEGER.

LARGE_INTEGER start, end, freq;

Now we are ready to set up the timer. First pick a place where you are wanting to start and stop your timer. Once you are sure insert the following pieces of code in the appropriate positions

QueryPerformanceCounter(&start); //To start the times

// Code here

QueryPerformanceCounter(&end);  //Same function stops the timer (notice different return variable)

LARGE_INTEGER numTicks=(end.LowPart – start.LowPart); // Save the number of ticks

The amount of time passed by is recorded in “ticks” rather than seconds or milliseconds, we can deal with this later. Ticks are units that relate to the processing speed of your CPU, therefore every machine will have different tick durations and tick speeds. Therefore we need a way to convert ticks into something useful. This is quite a simple calculation as we can query the processor to tell us how many ticks occur per second. This is achieved with the following code and should be placed right after the timer has finished…

QueryPerformanceFrequency(&freq);

So now we have two important numbers…

  1. numTicks
  2. freq (number of ticks per second)

A simple calculation brings us to the following result…

float elapsedTime = (float)ticks/frequency;

Where elapsedTime represents the number of Seconds the timer took!


1 Comment

Debugging full screen DirectX Applications

Today I was trying to step through some code for intialising a vertex buffer, as something was going drastically wrong along the way. However my application needed to be tested in full screen mode which made debugging through VS impossible as the application I was trying to debug takes full control of the screen.

There seem to be two solutions in this scenario;

  1. Modify your code to run in windowed mode (easy enough to do, just change your window class registration and DirectX initialisation routines)
  2. Use multiple monitors –> Goto control panel, choose DirectX, Goto DirectDraw tab, choose Advanced and enable Multiple Monitor Debugging.


Ajax Capabilities & Limitations

I have no official training or background in using Ajax technology, but do use it quite frequently when building web applications.

So far I have found it most effective when an AJAX call to a web service is triggered by the user. For example, they start typing in a search box and filtered results appear beneath, or perhaps they click “add comment” and that comment is posted asynchronously. This all works well and tidily through one javascript connection object, and never kicks up much of a fuss! However this post is more of a question than a solution.

My question is, what are the best practices to use for making continous timed calls to a web service / database?

I am currently building a web application where real time synchronisation between users is a key feature.

At first I wanted to approach this problem by using a technique whereby the client leaves an open connection to the web service, with the web service hooking this to a thread and delivering updates to the client (which i planned to achieve by sending JSON object code back and fourth). However, I was informed that this approach is not scalable and in-efficient on most web servers so i looked to polling.

The polling system I am now using means that the client will query the web server at (very) regular intervals in order to update the page. However I get problems when im doing a post to the webserver (perhaps posting a comment) and the page is auto polling in the background. I also have the question, how often should I asynchronously query the web server in order to keep efficient? Should I use separate connection objects in javascript to handle posts and queries? (although i dont think multiple http objects is an option in IE7? ).

As I mentioned my reading and study in this area is limited. I appreciate I could find tutorials on line and try and sequentially find information to answer my own questions, but expect that those who have experience can guide me (and other blog readers) on the orthodox way to do things when it comes to asynchronous web technology!

Anyone can appreciate that the technology here is very powerful. Only a few days ago Apple announced mobileMe and me.com which looks incredible, and very fast! A perfect example of the results I am trying to accomplish in my current project.


Ajax Capabilities & Limitations

I have no official training or background in using Ajax technology, but do use it quite frequently when building web applications.

So far I have found it most effective when an AJAX call to a web service is triggered by the user. For example, they start typing in a search box and filtered results appear beneath, or perhaps they click “add comment” and that comment is posted asynchronously. This all works well and tidily through one javascript connection object, and never kicks up much of a fuss! However this post is more of a question than a solution.

My question is, what are the best practices to use for making continous timed calls to a web service / database?

I am currently building a web application where real time synchronisation between users is a key feature.

At first I wanted to approach this problem by using a technique whereby the client leaves an open connection to the web service, with the web service hooking this to a thread and delivering updates to the client (which i planned to achieve by sending JSON object code back and fourth). However, I was informed that this approach is not scalable and in-efficient on most web servers so i looked to polling.

The polling system I am now using means that the client will query the web server at (very) regular intervals in order to update the page. However I get problems when im doing a post to the webserver (perhaps posting a comment) and the page is auto polling in the background. I also have the question, how often should I asynchronously query the web server in order to keep efficient? Should I use separate connection objects in javascript to handle posts and queries? (although i dont think multiple http objects is an option in IE7? ).

As I mentioned my reading and study in this area is limited. I appreciate I could find tutorials on line and try and sequentially find information to answer my own questions, but expect that those who have experience can guide me (and other blog readers) on the orthodox way to do things when it comes to asynchronous web technology!

Anyone can appreciate that the technology here is very powerful. Only a few days ago Apple announced mobileMe and me.com which looks incredible, and very fast! A perfect example of the results I am trying to accomplish in my current project.