I did a post some time ago on a threading library called TinyThread++. You can find it here.

Like always, the following is just a collection of notes.

Item 1: TinyThread++ is an almost functionally equivalent alternative to C++11 threads, but instead of taking multiple arguments to the thread it takes a single void*. When C++11 support improves everywhere, that will be the time to switch. But in the meantime, a void* is a good compromise.

Item 2: Whenever I describe how and why a member function is different than a global/static function, I often say that a member function has a “secret 1st argument, the ‘this’ pointer”. Heck, if I was going to build a C++ compiler, I would implement it like this. So for the longest time I just assumed this is how others implemented it.

If this is true, then it should be possible to convert a member function in to a “void Func(void*)”.

* * *

Long story short, this behavior is forbidden by the C++ standard. That said, it works in GCC, but fails in MSVC. In GCC’s case, while it does work, it invokes a warning known as “pmf-conversions”. You can explicitly disable the warning with “-Wno-pmf-conversions”, but given that this just doesn’t work in Visual Studio it’s probably unwise to do in the first place.

My nice solution was to add a static proxy function that takes a single “this class” pointer, and call the function as if it was a member of the class (because it is).

#include <stdio.h>

class TheClass {
public:
	void MemberFunc() {
		printf( "My This Addr: 0x%x\n", this );
	}
	
	// Static Wrapper Function //
	static void stMemberFunc( TheClass* th ) {
		th->MemberFunc();
	}
		
	inline TheClass* GetThis() {
		return this;
	}
};

typedef void (*FVoidPtr)(void*);

int main( int argc, char* argv[] ) {
	TheClass Instance;
	Instance.MemberFunc();
	
	//FVoidPtr Func = (FVoidPtr)&TheClass::MemberFunc; // GCC Only, -Wno-pmf-conversions
	FVoidPtr Func = (FVoidPtr)&TheClass::stMemberFunc;
	
	//Func( (void*)&Instance ); // Doesn't Work //
	Func( (void*)Instance.GetThis() );

	return 0;
}

This is the basic idea.

Improvements

Some of these improvements are certainly arguable. In fact, I’ll argue them myself.

Void pointer GetThis()

This is a minor one, since the concept of the GetThis() function is only for getting the ‘this’ pointer to be converted to a void pointer.

inline void* GetThis() {
		return (void*)this;
	}

	// ... //

	Func( Instance.GetThis() );

What’s arguable about this is GetThis() loses the type data. In practice, there really isn’t any reason to get the ‘this’ pointer from a class unless you plan to cast it to something else. The main benefit of this is that the function GetThis() can now be defined via a macro without any knowledge of type.

#define DEFINE_FUNC_GetThis() \
	inline void* GetThis() { \
		return (void*)this; \
	}


class TheClass {
public:
	void MemberFunc() {
		printf( "My This Addr: 0x%x\n", this );
	}

	static void stMemberFunc( TheClass* th ) {
		th->MemberFunc();
	}

	DEFINE_FUNC_GetThis();	
};

Thistype type

Alternatively, we can fake C++ having a ‘thistype’ feature by adding a general typedef to a class.

class TheClass {
public:
	typedef TheClass thistype;

	void MemberFunc() {
		printf( "My This Addr: 0x%x\n", this );
	}
	
	static void stMemberFunc( thistype* th ) {
		th->MemberFunc();
	}
	
	inline thistype* GetThis() {
		return this;
	}
};

Furthermore, if we do this often enough, we can simplify this code with Macros.

#define DEFINE_thistype( __name ) \
	typedef __name thistype

#define DEFINE_GetThis() \
	inline thistype* GetThis() { \
		return this; \
	}

#define DEFINE_STATIC_MEMBER_FUNC( __name ) \
	static void st ## __name( thistype* th ) { \
		th->__name(); \
	}


class TheClass {
public:
	DEFINE_thistype( TheClass );
	DEFINE_GetThis();

	void MemberFunc() {
		printf( "My This Addr: 0x%x\n", this );
	}	
	DEFINE_STATIC_MEMBER_FUNC( MemberFunc );	
};

Template version

This can be done in a rather neat and tidy way with C++ templates.

#include <stdio.h>

typedef void (*FVoidPtr)(void*);

template<class Type>
class tAction: public Type {
public:
	static void stAction( tAction* th ) {
		th->Action();
	}
	
	inline tAction* GetThis() {
		return this;
	}
	
	inline static FVoidPtr GetAction() {
		return (FVoidPtr)&stAction;
	}
};


struct MyAction {
	void Action() {
		printf( "My This Addr: 0x%x\n", this );		
	}
};


int main( int argc, char* argv[] ) {	
	tAction<MyAction> Me;
	Me.Action();
	
	FVoidPtr Func2 = Me.GetAction();
	Func2( Me.GetThis() );

	return 0;
}

Unfortunately, the above is limited to only a single function of a specific name.

That said, this is totally fine for wrapping a simple oneshot thread (like with TinyThread++).

#include "TinyThread/tinythread.h"
using namespace tthread;

int main( int argc, char* argv[] ) {
	tAction<MyAction> Me;
	Me.Action();

	thread t( Me.GetAction(), Me.GetThis() );

	t.join(); // Wait until finished //

	return 0;
}

And at the end of the day, this is what I was aiming to do anyway.

I’m free to add members to and operate on the data contained inside MyAction. I can set flags and add functions for checking the status of the Action;

Either directly to the Template Action:

typedef void (*FVoidPtr)(void*);

template<class Type>
class tAction: public Type {
	bool Started;
	bool Finished;
public:
	tAction() :
		Started( false ),
		Finished( false )
	{
	}

	static void stAction( tAction* th ) {
		th->Started = true;
		th->Action();
		th->Finished = true;
	}
	
	inline tAction* GetThis() {
		return this;
	}
	
	inline static FVoidPtr GetAction() {
		return (FVoidPtr)&stAction;
	}

	inline const bool IsStarted() const {
		return Started;
	}

	inline const bool IsFinished() const {
		return Finished;
	}
};

Or to my Action directly:

class MyAction {
	bool Ready;
public:
	MyAction() :
		Ready( false )
	{
	}
	
	void Action() {
		printf( "My This Addr: 0x%x\n", this );		
		Ready = true;
	}

	inline const bool IsReady() const {
		return Ready;
	}
};

Or both.

Horrible Legacy Lambda Function

As it turns out, this is supported in MSVC 2008, and GCC as long as C++11 is enabled (–std=c++11 or –std=c++0x).

int main( int argc, char* argv[] ) {
	struct MyAction {
		void Action() {
			printf( "My This Addr Yo: 0x%x\n", this );
		}
	};
	
	tAction<MyAction> Me;
	Me.Action();
	
	thread t( Me.GetAction(), Me.GetThis() );

	t.join(); // Wait until finished //

	return 0;
}

I’m assuming this will work in Clang in C++11 mode as well.

Inline MemberFunc() and Action()

None of the above samples have the inline keyword before MemberFunc() or Action(). I did this because I started out wanting to do this and be GCC ‘pmf’ compatible (which means the member function must exist at a specific address and cannot be inline). As a result, we’ve technically reimplemented how C++ virtual functions work. I haven’t bothered checking, but my brain seems to want to tell me that, best case, the above code should generate a similar number of instructions as typical C++ virtual functions. However, by inlining MemberFunc and Action, the functions should automatically collapse themselves in to stMemberFunc and stAction, thus requiring only a single function call: to the static function. Otherwise, the static function is called, then the member function is called.

Again, none of this is verified, but theoretical optimization says the only dependency that requires a function exist at an address is the static version (that we get a pointer to).

Functors

As it turns out, my template example above works similarly to Functors. Boost and Loki provide implementations, and usage is much the same, but you overload the ‘()’ operator.

struct MyAction {
		void operator () () {
			printf( "My This Addr Yo: 0x%x\n", this );
		}
	};

Thanks Andy.

My Functor

I’ll admit, I haven’t tested the alternatives (Boost, Loki), but from what I’ve been reading typical Functors don’t work like I want. Plus, they all have various overheads to them (virtual function storage, calls, etc). So here’s my proposed alternative. Zero overhead, C function pointer friendly, and whatnot.

MyFunctor.h:

#ifndef __MY_FUNCTOR_H__
#define __MY_FUNCTOR_H__

typedef void (*FVoidPtr)(void*);

template<class Type>
class Functor: public Type {
	static void StaticFunc( Functor* th ) {
		th->operator()( );
	}
public:
	
	inline Functor* GetThis() {
		return this;
	}
	
	inline static FVoidPtr GetFunc() {
		return (FVoidPtr)&StaticFunc;
	}
};

#endif // __MY_FUNCTOR_H__ //

SampleCode.cpp:

#include <stdio.h>
#include "MyFunctor.h"

struct MyFunc {
	inline void operator()( ) {
		printf("Hi 0x%x\n", this);
	}
};


int main( int argc, char* argv[] ) {
	Functor<MyFunc> Func;
	Func();
	
	FVoidPtr FuncPtr = Func.GetFunc();
	FuncPtr( Func.GetThis() );

	return 0;
}

Where this is meaningful is when dealing with C callbacks. Practically every callback system supports passing a data pointer to the function pointer you registered as the callback. So we’ve create a static function to act as a proxy that meets the requirements of being a ‘void(*)(void*)’ type (i.e. takes one pointer argument). That argument is expected to be the ‘this’ pointer of the class instance you’re trying to run as a callback. With that, all we have to do is call the desired function from the proxy through the pointer and we get full access to all the members of the class (without having to pass them as additional arguments).

From what I gather, a functor in a C++ sense is an instanced function with stored data. You get this by expanding the “MyFunc” class mentioned above. You can add additional functions as well, including a constructor and destructor. Each instance is isolated, making them as thread safe as you the user choose to make them.

Boost and Loki refer to the actual instancing call as a function called “function”, but IMO that just isn’t weird enough of a name. Technically the “MyFunc” class is the functor, and it’s totally usable without the Functor template, but instancing with the Functor template can be thought to create a complete Functor.

There are some callback situations where a callback takes multiple arguments, meaning the ‘StaticFunc’ above isn’t suitable for them. In my case, the idea of receiving a ‘this’ pointer inside ‘StaticFunc’ is essential to the design, and the position of the ‘this’ pointer needs to match the position of the callback’s data pointer. Boost uses a FunctionN (Function1, Function2, …) syntax to say how many arguments there are. In my case, where the ‘this’/data pointer goes is fundamental. I could potentially copy the syntax idea, but I will need a way of saying whether the data pointer is at the front or the back of the argument list (or worst case: anywhere). It *may* be possible to simply ignore arguments past a certain point, but given that function calls are stack based and different on different architectures (on ARM, several arguments go in registers and the rest go on the stack), it may be unwise. For the truly insane, calling format may be controllable with __attribute__’s (cdecl, etc). No thanks. I’ll stick with the simple design above, until I really need it to change.

Conclusion

I’m not sure why, but whenever I had to deal with member functions and function pointer in the past, I ended up butchering the class in to some sort of singleton bastardization, or series of globals. The above are several nicer, cleaner, and threading ready alternatives that I like better. 🙂