Category Archives: Programming

/clr and nonmanaged libraries

With Visual C++ mixing managed and unmanaged code is always interesting. It either just works, or your application dies horribly before reaching the main entry point. Debugging in the pre-main world of static data registration and atexit handlers is not very fun. Fortunately a post made by Jeffrey Tan of Microsoft Online Community Support provides a solution:

By further discussing with a developer from VC++ team, he confirmed that
this was a known issue. The main problem here is that the IDE is specific
the entry of ManagedApp as “main”. However, using “main” will bypass a lot
of CRT’s startup initialization. The fix here is to simply change the
entry point in the IDE. Under ManagedApp -properties-link -advanced,
change “entry point” from “main” to
“?mainCRTStartupStrArray@@$$FYMHP$01AP$AAVString@System@@@Z”. That should
re-enable the CRT startup code which initializes the internal CRT variables.

Original discussion can be found here.

[c++] Sneakily updating base classes

Recently I needed to update data in a base class, but only for types derived from that class.

struct Base {
	void Func() { cout << "Base::Func calledn"; }
};

struct Child : public Base { };

struct AnotherStruct { };

For example I want to call Base:Func() for all types that have been derived from Base. In the code above this would include Child and Base, but not AnotherStruct. If I've been given AnotherStruct then I don't want to do anything.

void call_base_func( Base* base ) {
	base->Func();
}

void call_base_func( void* ) { }

Thanks to function overloading this can be solved easily. Passing a Child to call_base_func will result in the first function being called, while AnotherStruct will use the second function.

But what do we do if Base is using the Curiously Recursive Template pattern?

template 
struct Base {
	void Func() { cout << "Base::Func calledn"; }
};

struct Child : public Base { };

struct AnotherStruct { };

Well now the type of Base is dependent on the type of Child. This breaks our previous solution as we can't specify Base without also specifying a type. Or can we?

template 
void call_base_func( Base* base ) {
	base->Func();
}

void call_base_func( void* ) { }

Sure we can. If Base is going to use templates, then so can call_base_func. As an added bonus we also get the type that initially derived from Base.

-

An example of this technique is with smart pointers. More specifically if you have a look a Boost shared_ptr it provides an enable_shared_from_this base class. This class tracks references to the derived object and allows you to acquire a corresponding shared_ptr to that object. The only way this can function is if the shared_ptr class can update the internal data in enable_shared_from_this, and only when the type is derived from enable_shared_from_this.

[c++] Cross thread communications – Part II

Recently I’ve been playing around with managed C++ and the .net framework. As usual I have one thread wanting to instruct a separate GUI thread to perform some task. In .net world with the help of delegates (glorified function pointers) this behaviour is easy.

First define the function to call:

///  update text box text from another thread
void MyGuiClass::updateText( System::String^ text ) {
	// show text
}

then define a delegate:

public delegate void GuiUpdateTextDelegate( );

and finally invoke the delegate from another thread:

BeginInvoke(
	gcnew GuiUpdateTextDelegate(
		this, &MyGuiClass::updateText, gcnew Systen::String("new text")
	)
);

While I’ve used BeginInvoke here, you should be aware that there is also an Invoke method. Invoke will wait until the delegate has been invoked, while BeginInvoke won’t and is asynchronous.

Bacteria v0.14

While showing off my screen saver today I discovered that Bacteria doesn’t support multiple monitors… or should I say didn’t. The fix entailed reading the release notes to discover that the change had already been made! Somehow the newer version had never been officially released, and left sitting on my hard drive for several years instead. This has now been rectified.

You can download Bacteria v0.14 from my programs page.

[c++] Cross thread communications

With GUI development it is not unusual to have several threads of execution running at one time. Normally one of those threads is dedicated to handling the user interface, while the remaining are used for auxiliary tasks. Unfortunately this can cause problems if you need to update the GUI from one of those other threads.

Typically SendMessage (part of the win32 api) is to used to notify the GUI thread, which then looks at the message id and acts accordingly. As you add more messages you need to add more message ids. Then there’s the greater problem of passing data between threads and the associated synchronization problems.

Fortunately there is another way using our old friend the command pattern:

///  update text box text from another thread
void MyGuiClass::UpdateTextBox(const std::string& text) {
	class GuiCmdUpdateTextBox : public GuiCmdBase {
	public:
		GuiCmdUpdateTextBox(MyGuiClass& gui, const std::string& text)
		: gui_(gui), text_(text) {  }

		virtual ~GuiCmdUpdateTextBox() { }

		// function operator is called by the GUI thread while processing the message
		virtual void operator()(void) {
			gui_.TextBox.SetText(text_);
		}
	private:
		MyGuiClass& gui_;
		const std::string& text_;
	};

	// send a message to the GUI thread and block until it has been processed
	gui_send_command( GuiCmdUpdateTextBox(*this, text) );
}

Using this method we have both the message sender (gui_send_command) and handler (GuiCmdUpdateTextBox::operator()) within the same function. This is a huge win, considering that we’ve also solved the data passing issue as it is neatly bundled up within the functor. You can see exactly what it is doing and what is needed to do it.

As for the magical wrappers that make all this happen:

/// pure virtual base class for GUI commands
struct GuiCmdBase {
	virtual ~GuiCmdBase() { }
	virtual void operator()(void) = 0;
};

GuiCmdBase is a straight forward pure virtual functor. By using a virtual function we no longer have to manage message ids.

/// send a GUI command across threads
void gui_send_command(GuiCmdBase& cmd) {
	// 1) add item to queue
	// 2) notify GUI thread that there is an item on the queue
	// 3) wait for command to be processed
}

gui_send_command is responsible for the actual sending and as such is library dependent. You have to queue the command to be processed and then notify the GUI thread. While you could just pass the pointer directly to the GUI thread this can be a very bad idea. Especially in win32 land where other applications can send you messages… In those cases I prefer a simple queue that you can retrieve pointers from.

// GUI thread message processing:
case MSG_GUI_CMD:
{
	GuiCmdBase* cmd = get_next_guicmd_from_queue();
	if (cmd) (*cmd)();
	break;
}

Once notified all the GUI thread has to do is call the provided functor.

I’ve successfully used this technique with win32, Qt, and wxWidgets.

[c++] Commenting tricks

When tracking down a compilation problem or even while refactoring code; I find it extremely useful to selectively disable blocks of code. Now I could just wrap the offending section in a ‘#if 0’ and change the 0 to a 1 as needed. Unfortunately not many IDE’s colour these sections correctly, and those that do sometimes get it wrong. Instead I prefer the good old block comment method:

some code
/*
commented code
// */
more code 

Notice how the line with the end of the block comment ‘*/’ has been preceded with a line comment ‘//’? This way you can comment out the start of the block comment with a single slash and not get an error from the unmatched end:

some code
//*
no longer commented code
// */
more code

I realise this is a fairly obvious “trick”, but I haven’t seen it mentioned anywhere else.

Error free programming

So the latest Ask Slashdot was concerned with writing ultra stable software in C++. Of course you have the usual anti-C++ crowd immediately crawl out of the wood work but there was one post that was interesting… well ok not the post itself but the link they referred to was: They Write the Right Stuff.

In brief the article refers to the work of the “on-board shuttle group” and their software defect rate. I’ve had this very article mentioned to me several times before by a work colleague and only now have I actually gotten around to reading it. The most interesting part of the article was not what it said but what it didn’t. Notice at no stage was the programming language they used mentioned. Why? Because it is not relevant. In essence the trick to achieving 99.9% reliability is process control.

Infact I’m confident that the “on-board shuttle group” will pass the The Joel Spolsky test.