Rules for Migrating C++ to C#
Since I’m about to describe a mechanism for porting C++ to C#, we need some rules for conversion. Without further ado, let’s get these pesky rules out of the way!
One of the major differences between C++ and C# is that C# is a managed language. This means that C# code is similar to Java in that it supports garbage collection. You won’t see pointer manipulation in C#, nor will you see calls like delete(). The runtime system takes care of these details. This presents a small problem: If you have pointer code in your C++ (as we have in Listing 2), how can you move that code into the C# domain? Does this code have to be rewritten? This is an important question, since you may have invested heavily in writing the C++ code. Can you get the best of both worlds—continue to use your C++ code but gain access to the capabilities of the C# language and the .NET platform? Fortunately, you can; you just move the C++ code by making use of the unsafe directive.
Better to Be Unsafe (Sometimes)
Configuring the C# project for unsafe code is very simple:
- Click Project.
- Click Project Options.
- Click the checkbox Allow Unsafe Code.
If you prefer to build from the command line, just include the /unsafe flag as an argument. At this point, you should be able to build the project successfully, as shown in Figure 1. Notice the three warnings in Figure 1, though; as is always the case for compiler warnings, these are useful helpers!
Figure 1 The basic (now-compiling) project, with warnings but no errors.
Two of the warnings in Figure 1 just relate to unused symbols—they’re defined but not used. This is a useful Java-like reminder about symbols that may be redundant. You can delete the symbols or make use of them. The other warning concerns the way in which the command pattern is structured. Basically, this warning tells you that a symbol was declared with the same name as a symbol in a base class—without using the new keyword. This warning informs you that you should use the new keyword. Figure 2 shows the result of inserting the new keyword—now we’re down to just two benign warnings.
Figure 2 Using the new keyword.
By allowing unsafe code, you’ve paved the way for migrating the pointer-related C++ code into C#. Bear in mind that having the ability to manipulate pointers in C# can get you into trouble. Be careful!