Archive | Namespaces RSS for this section

Back in the Saddle with C++

Next quarter, I’ll be taking a graphics programming class. It was a year ago to the day that I last wrote about getting a makefile set up for OpenGL development. As you can imagine nothing came of it. Why? The obvious answer is that OpenGL is hard.

Secondary answers include the fact that almost all of the literature is assuming C++, and I was swimming against the tide trying to use C. Well, I won’t have a choice this time, the class is in C++, so I’m stuck with my old nemesis again.

What follows in the next few posts is an attempt to refamiliarize myself with C++. It’s been a while since I’ve done any significant work in C++ and a lot has happened. I’ll be going over a lot of basic stuff, so that I have a centralized crash course for myself when I’m stuck trying to remember if it’s const &, & const, & const &, or co&n&st (stranger things have happened).


First up: namespaces. Namespaces are a formalization of the c convention of writing functions called stuff like dmp_doStuff. First we can declare our namespace:

namespace dmp { void doStuff() }

…and we can call this function by doing dmp::doStuff(). This may involve an extra keystroke, but we can also use it like so:

using namespace dmp; doStuff(); doStuff(); doStuff(); while (stuffUndone()) doStuff;

<Template> Classes

Now that we got that out of the way, let’s get into the meat of it: template classes. First up, due to some incredibly unfortunate reason, a C++ template class has to go in the header file. This sad fact is one of C++’s many transgressions against society, but we’ll not worry about that for now.

To declare a class (inside of a namespace if you’re a good citizen):

namespace dmp { template <typename T> class frac { public: /* public stuff goes here */ private: T numer; T denom; /* and your privates go here */ }; }

template <typename T> would be omitted if this weren’t a template class. Here we declare a class frac with one generic type T. Our class has two private fields of type T. As we all know, class members are private by default, but I don’t like to rely on “default behaviors”, so it doesn’t hurt to make it explicit. Let’s add some public constructors:

frac(T inNumer, T inDenom) : numer(inNumer), denom(inDenom) {}; frac(const frac<T> & toCopy) : numer(toCopy.numer), denom(toCopy.denom) {};

Here we use initializer lists to populate the numerator and denominator. The first constructor takes two arguments of the same type (T), and the second is the copy constructor.

According to Microsoft, initializer lists are more efficient than assignment in the function body, which is why we prefer them here. There are certain cases where you must use an initializer list, and cases where you cannot use them. Your compiler will tell you if you mess this up.

Finally, let’s add a destructor:

~frac() {};

Here we have a marvel of software engineering. Since we really don’t have anything to destroy, we can let it do nothing. It should be noted that this destructor is not virtual, so it’s not really safe to extend this class (more on this another day).


Honestly, namespaces and constructors/destructors are two of my favorite features of C++. Simple, but helpful in eliminating boilerplate. I almost might be convinced to compile “C” with a C++ compiler to get these features. Coming up will be some features that I’m a bit more iffy about, such as operator overloading. however, when used appropriately, these things can also be good, more to come!

DMP Camera Module: Shooting For The Moon

So there I was; several hours into my work on the Camera module. I may have mentioned this before, but lack of documentation is a pet peeve of mine. Unfortunately, some times it can’t be avoided. Take libgphoto2. If you click that link, you’ll get taken to a doxygen website. Seems promising, right? Go ahead and poke around, things start to look less rosy as you do. Unfortunately, this seems to be the gold standard of PTP libraries for Linux, so there’s really nothing for it. Right?

Maybe Not

After hours of frustration, I decided to try something crazy. I opened up a command prompt and entered:

gphoto2 --capture-image-and-download

And you know what? My camera took a picture and downloaded it to the current directory. Maybe that’s the answer I’m looking for. DMP Photo Booth doesn’t need to do anything fancy. It just needs to take a picture.

Now, I had been planning to provide modules that call out into Lua to allow people to implement modules in Lua. However, this was always a back-burner project. The sort of thing that happens after version 1.0 is released. But with implementing a libgphoto2 Camera Module seeming like So Much Work, maybe it was time to get on it. At least, for the Camera Module.


So I committed and pushed my work on the Camera Module. I made a copy of it, and removed all the logic. After that, I committed it to the repository. It was officially official.

The first order of business was creating the lua script loader. I needed an init, finalize, and is_initialized function for lua, and a capture function. Let’s take a look:

(I’ve omitted error handling from these examples. If I didn’t they’d be 3 times as long and nobody wants to read that)

gint dmp_cm_lua_initialize() { dmp_cm_state = luaL_newstate(); luaL_openlibs(dmp_cm_state); luaL_loadfile(dmp_cm_state, DMP_CM_MODULE_SCRIPT); lua_pcall(dmp_cm_state, 0, 1, 0); lua_setglobal(dmp_cm_state, DMP_CM_NAMESPACE); lua_getglobal(dmp_cm_state, DMP_CM_NAMESPACE); lua_getfield(dmp_cm_state, -1, DMP_CM_MODULE); lua_pushcfunction(dmp_cm_state, dmp_cm_lua_console_write); lua_setfield(dmp_cm_state, -2, "console_write"); lua_getglobal(dmp_cm_state, DMP_CM_NAMESPACE); lua_getfield(dmp_cm_state, -1, DMP_CM_MODULE); lua_getfield(dmp_cm_state, -1, "initialize"); lua_pcall(dmp_cm_state, 0, 0, 0); is_initialized = TRUE; return DMP_PB_SUCCESS; }

First up is the initialize function. First, I initialize Lua and open the standard library. The call to luaL_loadfile loads the script and pops it onto the stack as a function, which is called by the subsequent call to lua_pcall.

If you’ve been following the blog, you may have noticed that I’m a fan of namespaces. I follow the GLib namespace style and use [NAMESPACE]::[APPLICATION/MODULE]::. I’ve decided that DMP Photo Booth modules implemented in Lua should do this as well. Lua doesn’t have actual namespaces as a language feature, but like most things, they can be approximated using tables. To that end a Lua camera module script should return a table named dmp, which contains a table named cm. In a future version, these will likely be configurable. The module will return the dmp dmp, which is set as a global in the next call.

Next, we must register the console write callback. This is accomplished by getting the table, pushing the console write function, and setting it as a field in

Next, we get, and call it.

gint dmp_cm_lua_capture(gchar * location) { lua_getglobal(dmp_cm_state, DMP_CM_NAMESPACE); lua_getfield(dmp_cm_state, -1, DMP_CM_MODULE); lua_getfield(dmp_cm_state, -1, "capture"); lua_pushstring(dmp_cm_state, location); lua_pcall(dmp_cm_state, 1, 0, 0); return DMP_PB_SUCCESS; }

This is the basic method to call a function. First, get the dmp table, then get its cm field. Next, get the function from After the function is on the stack, we push its arguments onto the stack, and finally we call it. The functions for finalize and is_initialized look strikingly similar, so I’ll spare you.

The Script

The script is extremely simple, thanks to Lua. I can print the whole thing here without editing it, it’s so small:

local dmp = {} = {} function os.execute("gphoto2 --capture-image-and-download" .. "--filename=" .. location) end function end function end function return true end return dmp

In the first two lines, we create our namespace tables. Next we define our functions: capture, initialize, finalize, and is_initialized.

Finally, we return our namespace table for use within C. Of the four functions, only capture isn’t a placeholder. In capture, we fork and execute gphoto2, signaling our camera to capture.

How’s That Working Out For Me

Unfortunately, not so great. Well, the Lua module works perfectly. It loads, all functions call without a hitch. And a Lua script is a lot easier to implement than a C module. If only gphoto2 wasn’t so incredibly brittle.

The problem with a command line utility is that you have to count on it to work. Unfortunately, so many things can go wrong with gphoto2. So many errors, so many ways to get into an inconsistent state. Plus, my favorite part about all of this, is that all of this happens by magic! You can do the same thing twice and get different results! Take that Einstein!

No, it seems that my little forray into Lua has come to an end. The Module is live. However, work must re-start on dmp_pb_camera_module. Such a shame…

DMP Photo Booth: Throw It All Out

Another week goes by, another major refactor. This time on the chopping block: return codes. As you may know if you’ve been following development, I’ve been using integer return values to indicate success and failure of functions. This was working for a while, but as we all know, the worst problems don’t rear their ugly heads until some time has gone by. After working around them, I’ve realized this strategy has 3 main issues:

  • It’s really easy to just not check the return value, and not notice when some function returns DMP_PB_OMG_WERE_ALL_GONNA_DIE
  • It can be problematic if you have to return an integer as an actual result
  • You have to settle on some “failure” return value for functions that return values, and this can be a problem if you can’t guarantee some value will never be valid

Too bad I didn’t pick a modern language with exception handling…

GError To The Rescue

Luckily for me, GLib has the answer once again. GLib has a feature called GError, that is its answer to exception handling. I’d tell you all about how to use GError, but there is no need. GLib’s documentation is on par with Java’s documentation, and the GError documentation page is a shining example of how good documentation can make the difference between good and great.

Seriously, if anybody from Gnome is reading this: thank you for writing some decent documentation. This is a huge pet peeve of mine. No, your function called do_stuff(some_struct * zanzibar) is not self documenting, because if you don’t write a comment telling me if it has side effects, or if I remain responsible for zanzibar, then I have to look at your code to be sure. But I digress…

The basic idea behind GError is that any function that can throw has a GError ** as its final argument. If you’d like to call a function that can throw, you need to pass in an unallocated pointer to the function:

void some_func() { GError * error = NULL; dangerous_func(&error); ...

At this point, dangerous_func will be called, and return. Afterwards, if your GError pointer is no longer NULL, then an exception was thrown:

if (error != NULL) { //what now? }

This test is equivalent to a catch {} block. At this point, you traditionally have 3 options: Handle the exception, re-throw the exception, or wrap the exception in some other exception type and throw.

Personally, I’m a huge fan of Java’s checked exceptions. Sure, it can be annoying having to catch 15 different exceptions because some library author thought they needed that many on one method, but it sure beats having to magically know if some function throws, as C++ handles things. I feel that GError strikes a good balance. If a function has a GError ** argument, then it throws. At this point, you can check the docs to see if the author felt fit to say what GErrors they set, or you can just read the error and see what it is. You don’t have to catch some specific Exception class as in traditional exception handling, and you can determine exception type without resorting to instanceof.

Now, let’s examine our options…

Handle It

if (error != NULL) { printf("%s %d: %s\n", g_quark_to_string(error->domain), error->code, error->message); g_error_free(error); }

A GError has 3 public fields: domain, code, and message. Domain is a GQuark that is [NAMESPACE]_[MODULE]_ERROR. Think of this as your exception base class: i.e. BaseBeanFactoryBeanException. Code is an integer that represents a specific error. Think of this as your derived exception class: i.e. FluffyPinkBeanFactoryBeanException Finally, we have message. This is a human readable message for the error, and is equivalent to a Java call to Exception.getMessage().

GError has a few methods to ease working with these, but any C programmer worth their salt should be able to “make do” with these 3 fields.

Re-throw It

if (error != NULL) { g_propagate_error(this_funcs_gerror, error); return; }

Yes, it is that simple. Of course, in this case, the function signature would be:

void some_func(GError ** this_funcs_gerror)

…but aside from that, there’s not much going on here. The GError will be copied into the passed-in GError **. At this point you can (must) return; the error is now the caller’s problem!

Wrap It

if (error != NULL) { g_set_error(this_funcs_gerror, error->domain, error->code, "I know better, so I'm wrapping this!\n"); g_error_free(error); return; }

Pretty self-explanatory. As with re-throwing the exception, this requires a modified function signature. Also, this is how you’d throw a new exception as well, minus the call to g_error_free.

The Empty Catch Block

We’re all guilty of this, don’t try to act like you’re not. It’s just so much easier to do this:

try { fancyObj.someDangerousMethod(); } catch (Exception ex) {}

Don’t worry, you’re among friends. GLib has you covered on this front as well. If you pass NULL to a function that throws, it will not attempt to set an error, and you can just go on with your life:

void some_func() { dangerous_func(NULL); //catch (Exception ex) {} }

Feel free to omit that comment, I promise it’ll still work. As we all know, sometimes you just don’t care about some exception. In these cases, you aren’t forced to care, you can just pass NULL and get on with your life.

Getting Fancy With Patterns: the Singleton

A while back, a bunch of people that have probably been doing this stuff longer than you or I wrote a book called Design Patterns: Elements of Reusable Object-Oriented Software. This book contains details about a set of “patterns” that describe how things are commonly done, and how to do them properly. One such pattern is the Singleton.

The singleton is basically a class that there must only ever be one instance of. It has been debated whether or not a singleton should be used; a quick google search of anything singleton related will turn up a torrent of Stack Overflow threads with all the commenters berating the OP for daring to use a singleton. What is not up for debate is how to implement one.

A singleton enforces its singularity using a few techniques: The singleton contains a static instance of itself in the class definition, all its constructors are private, and it has a static public method that returns a pointer to its static instance. Below is a sample header of a singleton:

#ifndef SINGLETON_H #define SINGLETON_H namespace clt { namespace patterns { class singleton { public: static singleton * get_instance(); static void destroy_instance(); ~singleton(); private: static singleton * instance; singleton(); singleton(const singleton& orig); singleton& operator=(const singleton& orig); }; } } #endif /* SINGLETON_H */

First, you’ll notice that all of our constructors, and operator= are private. Secondly, you’ll see the two static public methods: get_instance() and destroy_instance(). These two methods handle creation and deletion of the singleton. Also, I have a destructor. It is very important that you do not attempt to call delete instance from within the destructor! If you do this, you will get an infinite loop. However, you should still put all the rest of your destruction logic in the destructor. Below I’ll go over the implementation of these methods:

#include "singleton.h" using namespace clt::patterns; singleton * singleton::instance = 0; singleton * singleton::get_instance() { if (instance == 0) { instance = new singleton(); } return instance; } void singleton::destroy_instance() { delete instance; instance = 0; }

You may be wondering about the third line: singleton * singleton::instance = 0. This is required to for the initialization check in get_instance. If this line is not here to initialize it to 0, you’ll get compiliation errors. Unlike a normal class, you can’t put this in the constructor because this value is needed before construction.

The method get_instance() does two things. First, it checks to see that instance is not a null pointer. If it is, calls new singleton and assigns the resulting singleton to instance. Next it returns the instance pointer.

destroy_instance() is quite straightforward. First, it calls delete instance. next, it resets instance to 0 so that the singleton can be recreated by a call to get_instance().

…and that’s all there is to it. You now have all the tools you need to create your own singleton. Global variables will never be the same…

Implementing a Vector in C++: Working Smarter, Not Harder

You may remember when I created a vector in C. Yep, just another day in the life… How about we re-invent this wheel again?

This time we’ll be creating a vector in C++. This is much easier to do in C++ thanks to generics and operator overloading. Since this is a template class, we’ll be implementing the class in our .h file, forgoing the .cpp file. First we declare our class. Ensure that you declare it a template class.

namespace clt {
namespace dmp {

template <typename T>
class vector {



Remember namespaces? Gotta have those namespaces. Aside from that, nothing particularly special about this block. Next I’ll go over the methods and members of this class.

First up: our destructor. Nothing special going on here, we’re just going to delete our array pointer to ensure proper Resource Acquisition is Initialization (RAII). We’re going to let it be virtual to allow for subclassing.

virtual ~vector()
delete [] backing_array;

Next I’ll discuss the private method: initialize(). This method is called by all constructors and does 3 things: sets backing_array_size, resize_increment, and news up our array:

void initialize(const unsigned size, const unsigned increment)
backing_array_size = size;
resize_increment = increment;
backing_array = new T[backing_array_size];

Next up is our default constructor. It sets size and increment to 10. I like 10, it’s a nice, noble number. The kind of number you’d bring home to Mom and Dad:

initialize(10, 10);

Next we’ll talk about a private method: array_copy(). This method does pretty much what it says: it iterates through the original array and copies its contents into the new array:

void array_copy(T * orig_array, T * new_array)
for (int count = 0; count < backing_array_size; count++)
new_array[count] = orig_array[count];

Next to talk about is our copy constructor. It initializes the new vector with the old vector’s size and increment, then calls array_copy:

vector(const vector& orig)
initialize(orig.backing_array_size, orig.resize_increment);
array_copy(orig.backing_array, backing_array);

Moving along to operator=, which basically functions the same as the copy constructor, aside from the obligatory return statement:

vector& operator=(const vector& orig)
initialize(orig.backing_array_size, orig.resize_increment);
array_copy(orig.backing_array, backing_array);
return * this;

Next up: resize(). This private method creates a new T array sized backing_array_size+resize_increment. Then, it calls array_copy to copy the contents of the old array to the new. Finally, it increments backing_array_size by resize_increment, calls delete [] on backing_array, and sets backing_array to the new array:

void resize()
T * new_b_a = new T[backing_array_size + resize_increment];
array_copy(backing_array, new_b_a);
backing_array_size = backing_array_size + resize_increment;
delete [] backing_array;
backing_array = new_b_a;

Which brings us to operator[]. This method indexes into backing_array. If to_get >= size, it calls resize() until to_get is a valid index. It should be noted that this method does not prevent you from attempting to read into a null pointer:

T& operator[](const unsigned to_get)
while (to_get >= backing_array_size)
return backing_array[to_get];

Finally, we have a setter for resize_increment and a getter for backing_array_size:

void set_resize_increment(const unsigned to_set)
resize_increment = to_set;

const unsigned size()
return backing_array_size;

Lastly, this class has 3 private fields: a pointer array to the contents of the vector, the size of the array, and the resize increment:

T * backing_array;
unsigned backing_array_size;
unsigned resize_increment;

…and that’s all there is to it. No casting void pointers, no manual resource allocation, and no unweildly method names. Or you could just use std::vector I guess, but what would be the fun in that?

Configuring NetBeans Code Templates

So, I’m sitting there making a C++ class, minding my own business and…

#ifndef FOO_H
#define FOO_H

class foo {
virtual ~foo();
foo(const foo& orig);

#endif /* FOO_H */

What?! NO! Where are my 500 nested namespaces?! Why is this default constructor public?! Where is my operator=?! Why would they do this?! No wonder the cool kids use Eclipse…

Luckily for us, this is fixable.

First, launch NetBeans.

Click Tools->Templates

Click Settings. First, we need to create some custom properties. I like to use a universal top-level namespace, and a subject-specific namespace for my personal projects. Enter:


Save and close the tab. Click Tools->Templates. Expand C++, and click class.h. Click Open in Editor. You’ll see some suspiciously familiar text. Let’s go ahead and best practices it up:

#ifndef %<%GUARD_NAME%>%
#define %<%GUARD_NAME%>%

namespace %<%BASE_NAMESPACE%>%
namespace %<%SUB_NAMESPACE%>%
class %<%CLASSNAME%>%
virtual ~%<%CLASSNAME%>%();
%<%CLASSNAME%>%(const %<%CLASSNAME%>%& orig);
%<%CLASSNAME%>%& operator=(const %<%CLASSNAME%>%& orig);
#endif /* %<%GUARD_NAME%>% */

We’ve declared operator=, and we’ve moved the default constructor, copy constructor, and operator= into the private section. We’ve also added our namespaces. Save and close the class.h tab. While we’re at it, why don’t we update the Class.cpp file. Click Tools->Templates. Expand C++, and click C++ Class. Click Open in Editor. Let’s use our namespaces, and add our operator=:

#include %<%QUOTES%>%%<%NAME%>%.%<%DEFAULT_HEADER_EXT%>%%<%QUOTES%>%

using namespace %<%BASE_NAMESPACE%>%::%<%SUB_NAMESPACE%>%;

%<%CLASSNAME%>%::%<%CLASSNAME%>%() {

%<%CLASSNAME%>%::%<%CLASSNAME%>%(const %<%CLASSNAME%>%& orig) {

%<%CLASSNAME%>%::~%<%CLASSNAME%>%() {

%<%CLASSNAME%>%& %<%CLASSNAME%>%::operator=(const %<%CLASSNAME%>%& orig){


Save and close the C++ Class tab. Now, let’s try this again. Right click your project, and select New->C++ Class… You should now end up with a .cpp file and .h file that look like this:

#ifndef FOO_H
#define FOO_H

namespace clt {
namespace /*PLACEHOLDER*/ {

class foo {
virtual ~foo();
foo(const foo& orig);
foo& operator=(const foo& orig);
#endif /* FOO_H */


#include "foo.h"

using namespace clt::/*PLACEHOLDER*/;

foo::foo() {

foo::foo(const foo& orig) {

foo::~foo() {

foo& foo::operator=(const foo& orig) {


You’ll need to change /*PLACEHOLDER*/ to an actual name before you can use these files, but I like the red jaggies; makes it hard to forget to fix them. Regardelss, we now have a class template that’d make Scott Meyers proud!

%d bloggers like this: