Friday, January 23, 2009

Turning C++ into C#

Can you really turn C++ into C#?

The answer is yes to a certain extent, but you'll need certain C++ keyword extensions which are readily available in C++ compilers such as BCC (Borland / CodeGear C++ Compiler), namely indexed properties (VC++ does support properties via the __declspec(property) extension but does not support indexed ones).

What I've found really interesting is that it is quite possible to write templates and turn C++ objects into fully 'managed' - e.g. garbage collected, arrays are range checked and pointers are checked for null reference.

I've even went as far as to create templates for keywords such as C#'s 'using', 'foreach' and 'lock'. They behave exactly the same as their counterparts in C#, albeit with a little syntax difference for the 'using' and 'foreach' keyword.

The advantage of having a C# like C++ library will be greatly appreciated by programmers who love C# but would like their target application to run on non-dotnet platforms such as an embedded XP with limited RAM for cost reasons. Apart from that, applications based on this library will always outperform any C# applications since it's basically C++ with a garbage collector behind it. There are no managed / unmanaged switching penalty when pinvoking and the garbage collector is definitely more deterministic. I've made it such that it such that the code could temporarily disable the garbage collector. This makes real-time systems much more reliable than those using .NET.

With this library, it is a lot simpler to write high performance applications - glue logic could be written in C#Lib, and the core in pure C/C++ or ASM. With clear separation between managed and non-managed object within the same source code, the non managed part runs per usual, while the object itself could still be managed by C#Lib. The garbage collector also does not relocate objects - they rely on a low-fragmentation memory manager for memory allocations. The GC is a double edged sword in that it is faster and is also easier on the library user as calling into legacy code / APIs / code written in other languages for high performance as the objects always have a permanent address.

There are a few subtle things which C++ can't do but C# (or in a more generic term, .NET) can. For example, the multiple inheritance feature in C++ is rather limited. You can't explicitly override a method for a specific base class (even if it's implemented as an interface).

But the most important thing which C++ lacks is the garbage collector, which proved extremely useful in design patterns for the asynchronous (read multi/many core) future (actually, now). C#Lib bridges the gap and has proven to be extremely useful for me.