A path from C/C++ to C# and back to C++

About ten years ago I started my first full time programming job. I was working on some business software written in C/C++. I say C/C++ instead of just C++ because it was written mostly in C with classes – with perhaps a few cases of inheritance or actually even only few classes – it used structs in many places to group some methods together the same way you would use classes today. The code was fairly complicated and it was just aging. The standard C libraries it used were not very rich, so if you wanted to code up something fairly straightforward – you had to dig through a lot of documentation looking for something basic only to end up implementing that list class yourself. We were using a Watcom compiler at that time and trying out Borland C++ Builder for some side projects showed it was a great improvement in that VCL provided a lot of great wrapper classes for Windows APIs making things easier. Two years later we were looking into rewriting our application or at least starting a new version and considering which tools to use – basically trying to choose between Borland C++ and C#. I was on the C++ side – it was a fairly known language, more predictable and providing intuitively higher performance, while C# was at version 1.1 and had lots of great libraries, but a bit foreign and why would anyone want to go away from the fun of using pointers, managing object lifetimes and relying on some garbage (collector)? Well, I lost – Microsoft seemed to be focusing on supporting C# and in the end it turned out to be a lot more productive than C++.

Fast forward 8 years and Microsoft says – in Windows 8 you can code using C#/VB, JavaScript or C++. Well, the word on the street is that it is so that programmers fluent in any of these languages will be able to code applications for Windows, so I guess I will stick with C#. Maybe I will look at HTML5, JS and CSS, since these seem to be getting most traction, I thought. Now, having found some limitations in the .NET/WinRT stack I have a feeling like the C++/DirectX route is the most attractive. The .NET stack might make you more productive than the JS or C++ – especially if you have been coding in C# for the last eight years and perhaps HTML5 has better graphics performance or some other interesting features, but it feels like learning C++/DirectX on top of C#/WinRT is what would allow me to cover most scenarios for writing Metro Style Apps™, so especially with some experience working on the test team for the DirectX wrappers in the Windows API Code Pack – I am hoping to have an easier start in diversifying my skills.

C++ (Re)Learning Resources

Right now I have two resources I am using to relearn C++:

  • The Pluralsight C++ trainings by Kate Gregory – it is 10 hours of videos which is a bit painful, especially that the 7 hours of the beginner part is mosly familiar stuff targeted at the very beginners indeed, so that makes me a bit sleepy after a weekend day with the kids, but it is very high quality and I like to get solid basics before I start working with a technology, so I will make it through somehow! 🙂
  • The C# to C++–A Somewhat Short Guide by Michael McLaughlin – which I plan on going through when I am done with the Pluralsight videos as a review of sort, the subject seems to be just what I need after all! 🙂

DirectX Resources

Meanwhile I am slowly starting to look at DirectX, so I installed the last DirectX SDK from 2010. I think it is now part of the Windows SDK, but my Windows SDK install failed for some reason and it seems like the latest one for Windows 7 is actually older than the standalone one. It should also work OK with the Windows API Code Pack that I will review as a reference, since it has a lot of my C# code for the Direct2D samples which I will need to rewrite for Windows 8 in C++ to code a few things I have been thinking about. MSDN has some interesting samples worth looking at too.
I also installed NShader for HLSL syntax highlighting in Visual Studio, the Shazzam tool for HLSL coding. That’s it for learning on my Windows 7 box. On the Windows 8 boxes I will be limited to VS11 anyway until tool support happens and there – the Windows SDK should already be integrated with the DirectX one.

_codingStyle

After 10 years in the industry I am probably at my peak of caring about the coding style – having my own preferred style in C# – based on ReSharper and StyleCop, but with one parameter/condition per line if all don’t fit in a line. Since C++ does not seem to have a leading style, at least according to WPF Disciples’ resident DirectX expert – Jeremiah Morrill, I am going to try to adopt my C# style to the C++ code and see what comes out. While C# has a few controversial best style options in a couple areas – it is mostly Pascal/camelCased. C++ on the other hand seems to be all over the place, so at least having my own code based in the familiar style might help me orient myself in the world of double colons and pointer arrows…

Having mentioned ReSharper – I really feel like the C++ editor could do more in terms of IntelliSense even if it is not a managed language with all the metadata available. It seems like there are tools that enhance the VS C++ editing experience too. ReSharper is not one of them, but I picked up a trial of Active Assist X and it seems to improve things quite a bit.

C# -> C++/CLI -> Native C++

As the first piece of coding I thought I’d do some comparison between C# and C++ as well as between the managed C++/CLI and the native C++. How long might it take to go through a long loop of integer increments in each of these? Well, it seems like it is rather quick these days with 2 billion iterations taking only 6s in C# and 5s in C++ or C++/CLI to execute the below loop!

for (int i = 0; i < 2000000000; i++);

While this is not a representative piece of code at all – it just shows how closer to the metal C++ is (probably having each iteration take 5 cycles as opposed to 6 cycles for C#). See the measurement code and output samples.

C#

for (;;)
{
    var start = DateTime.Now;
    Console.WriteLine("Start");
    for (int i = 0; i < 2000000000; i++);
    Console.WriteLine("End");
    var duration = DateTime.Now - start;
    Console.WriteLine("{0:F3}s", duration.TotalSeconds);
}

Output

C# sample output

C++/CLI

for (;;)
{
    {
        DateTime& start = DateTime::Now;
        Console::WriteLine("Start");
        for (int i = 0; i < 2000000000; i++);
        Console::WriteLine("End");
        TimeSpan& duration = DateTime::Now - start;
        Console::WriteLine("{0:F3}s", duration.TotalSeconds);
    }

    {
        clock_t start = clock(), diff;
        std::cout << "Start" << std::endl;
        for (int i = 0; i < 2000000000; i++);
        std::cout << "End" << std::endl;
        diff = clock() - start;
        float sec = (float)diff / CLOCKS_PER_SEC;
        std::cout << sec << "s" << std::endl;
    }
}

I have used C++/CLI to a very limited degree before. Looking at the sample above you can see how easy it is to port some basic C# code to C++/CLI which allows you to keep using the so convenient .NET Base Class Library (BCL) while also being able to use the native libraries.

Output

C++/CLI sample output

Native C++

for (;;)
{
    clock_t start = clock(), diff;
    std::cout << "Start" << std::endl;
    for (int i = 0; i < 2000000000; i++);
    std::cout << "End" << std::endl;
    diff = clock() - start;
    float sec = (float)diff / CLOCKS_PER_SEC;
    std::cout << sec << "s" << std::endl;
}

Output

Native C++ sample output

Summary

C# is the most productive and best looking language I have ever used and sure – it is a general purpose language in that you can use it to do all sorts of things, but you can’t do everything in C#, at least not if you want to do some types of Metro Style Applications for Windows 8. Native C++ and DirectX is supported for use in Metro Style Applications, but C++/CLI is not and I don’t believe you can use managed wrappers with DirectX to make them, so if you want to make games for Windows 8 – forget Managed DirectX, XNA, SlimDX, Code Pack and SharpDX. It’s back to C++ baby! 🙂

(EDIT) Notes on C++/CX

MSDN has a Quick Reference page, that shows how C++/CX types map to Standard C++ types.

Other interesting articles:

Advertisements
Tagged , , , , , ,

6 thoughts on “A path from C/C++ to C# and back to C++

  1. I would be extremely careful about comparing C++ and C# code… When you will start playing with optimization settings, you might get completely different results. I would not be surprised at all if in some cases, aggresive optimization would skip the whole loop!

    Also, C# is running under VES (Virtual Execution System) and that means that it might do some additional optimizations after some time of collecting stats. I don’t know what exactly is done there, but Java Virtual Machine is constantly observing the executed code and if some code paths are not executed, they are being simply removed. I guess the same thing might happen for .NET apps, I guess the exact .NET version also matters.

    • xyzzer says:

      Thanks for the comment! This was not really a test to compare the speed of C++ vs. C# in general or even to test anything relevant to making decisions between choosing one language over the other. Since you are talking about virtualized execution here – this is just one more point that shows how using a native language might be a good option at least in some cases. If say I just want to copy some bits – I don’t think being run in any sort of virtualization might help speed it up.

  2. [“but you can’t do everything in C#, at least not if you want to do some types of Metro Style Applications for Windows 8.”]
    There is currently no restriction in any way that limit the kind of Metro Style App in C#.

    [“Native C++ and DirectX is supported for use in Metro Style Applications, but C++/CLI is not and I don’t believe you can use managed wrappers with DirectX to make them”]
    SharpDX gives access to the whole DirectX API from C# and you can develop Metro style App with XAML-DirectX interop flawlessly..For example, the application “Solitaire” on Windows 8 Consumer Preview is using SharpDX and was developed in C#.

    Apart from that, I agree with Tomasz, micro-benchmark is tricky and you can get wrong figures (depending on the compiler flags, if you ran your code in debug or release – benchmark must be always done in release…etc.), but that being said, compiled C++ should be always faster than C# from 1.1 to x2/x3 depending on the application, optimizations settings and so on. Also, unlike Java JVM, the .NET JIT is done once the first time a method is running, there is no re-jit.

    But yeah, in the end, use the language where you feel that your creativity is not limited and you feel comfortable with productivity! 😉

  3. xyzzer says:

    Thanks for the comment, Alexandre and thanks for your great tools! Regarding your comments…

    [“but you can’t do everything in C#, at least not if you want to do some types of Metro Style Applications for Windows 8.”]
    {There is currently no restriction in any way that limit the kind of Metro Style App in C#.}
    I think what I meant to say was – “you can’t do everything with C# with XAML”. There is no overall limit, but I think Javascript applications don’t have access to the XAML UI stack and vice versa for .NET languages or C++ with HTML5. There are also different performance profiles and development costs for doing same sort of applications using these different languages to say nothing about bugs or limitations of different stacks.

    [“Native C++ and DirectX is supported for use in Metro Style Applications, but C++/CLI is not and I don’t believe you can use managed wrappers with DirectX to make them”]
    {SharpDX gives access to the whole DirectX API from C# and you can develop Metro style App with XAML-DirectX interop flawlessly..For example, the application “Solitaire” on Windows 8 Consumer Preview is using SharpDX and was developed in C#.}
    I guess when I was writing this post – I did not know you had a version of SharpDX for WinRT in the works (I also don’t see an available SharpDX release for Consumer Preview yet) and the other wrapper libraries might likely not get their WinRT versions for a while anyway. Now it seems that technically I am wrong.
    The point is though – all the (limited) official documentation for DirectX and most samples are still mostly available only for C++, so even if I decide to use SharpDX – I will still need to translate the C++ documentation or samples to SharpDX before I will learn how to use it and to translate it – I might need to dig into SharpDX to see how it works internally. Eventually I will likely become more productive doing DirectX through C#, but then I am still going through another layer with a one-person support team… Not that Windows API Code Pack ever had a big support team behind it 🙂 but until SharpDX or another future .NET library that gives you access to DirectX in WinRT gains enough critical mass – you still need to learn some C++ to do DirectX development.

    All things said – I am looking forward to trying out SharpDX. I have been trying to mix the Media Foundation and DirectX using C++ last week and even having seen some success – I am tired of “::”, headers and the horrible mix of naming conventions of the native world… 🙂

    How can I use SharpDX with Consumer Preview today?

  4. Indeed, if you want to learn DirectX, you have to understand the whole C++ API, this is the only way to use it efficiently. SharpDX is intended for C# (lover) programmers with a knowledge about the whole underlying C++ DirectX API (I wrote a response few weeks ago about a similar question: http://pastebin.com/RcVFRVm5). And yes, for example, all Direct2D samples in SharpDX were ported from C++ samples, nothing complicate to do, but much more concise and pleasant to read and program with.
    About SharpDX and consumer preview, it is being updated, latest source code is already providing DirectX-XAML interop, but an official version will be released later in April.
    And yeah, if you love C#, you will recall why C++ is just mostly full of garbage. 😉

  5. Developer says:

    Are you professional writer? Do you have any books or published articles? Just wondering, because it is great post. Can I use it on http://www.hackishcode.com ?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: