Managed C++/CLI Programming: Part 1

Abstract

This wonderful article explains the theory and principle behind C++/CLI programming under the .NET Common Language Runtime (CLR) context. We shall investigate the remarkable features of C++/CLI programming, for instance its advantages over the native C++ language and the CLR context. We will run through the basic mechanisms to create and execute a CLR console and other application prototypes using the Visual Studio 2010 IDE. We'll also explore the semantics of the C++/CLI language to write and implement code. This segment also covers various significant aspects of CLR C++ programming prototypes in details related to hardcore object-oriented programming.

Science of C++/ CLI

There are two fundamentally different kinds of C++ applications you can develop with VC++ 2010. You can write applications that natively execute on your computer. These applications are defined by ISO/ANSI language standards, referred to as native C++ programs. You can also write applications to run under the control of the CLR in an extended version of C++ and ECMA defined 355 standards, called CLR programs or C++/CLI programs.

The CLR is an environment for the execution of managed programs written in a wide range of high-level languages including C#, VB and C++/CLI. The specification of the Common Language Runtime (CLR) is now embodied in the ECMA standard for Common Language Infrastructure (CLI). That is why C++ for the CLR is referred to as C++/CLI.

The CLI is essentially a specification for a virtual machine environment (the Virtual Execution System (VES)) that enables applications written in other high-level languages to be executed in different system environments without recompiling the source code. The CLI specifies a standard intermediate language (called MSIL) for the virtual machine to which the high level language source code is compiled. Code in MSIL is ultimately mapped to machine code by a JIT compiler when you execute a program. So, code in the CLI intermediate language can be executed within any other environment that has a CLI implementation.

Writing C++ Code

As we have noted earlier, you have two options for Windows applications; you can write code that executes with the CLR and you can also write code that compiles directly to machine code and thus executed natively. C++ code that executes with the CLR is described as managed C++ because the data and code is managed by the CLR such as the releasing of memory that you have allocated dynamically for storing data. That is taken care of automatically, thus eliminating the source of common native C++ errors. The C++ code that is executed outside the CLR is referred to as unmanaged C++.

So here C++/CLI posed a huge advantage over native C++ because with unmanaged C++ you must take care of all aspects of allocating and releasing memory during execution of your program yourself and also you need to shield your application from various security penetration breaches.

operating system

The big advantage of C++/CLI is the ability to mix native code with managed code. You can extend existing native C++ applications and add .NET functionality and you can add .NET classes to native libraries so that they can be used from other .NET languages such as C# and VB.

C++ / CLI “Hello world!” Project

This section explains the creation of a first “Hello World!” program in C+/CLI programming language using the Visual Studio 2010 IDE. Although this would the simplest logic implementation, we are just trying to display a string value by a CLR console base application like another C# console based application. Here is the tutorial procedure for that.

  1. First, ensure that the VC++ plugin is properly configured in your Visual Studio 2010 IDE. If not, then re-install the software and during that process choose the VC++ options.

    clr console application

  2. Open the Visual Studio 2010 IDE. Go the File Menu, select the New Project and you will find the VC++ language plugin in the dialog box left pane.

  3. Expand the VC++ and select CLR. Then, choose CLR console application from the right pane.

  4. Finally give a name to the project like “CLI_test” and finally press the OK button as in the preceding figure.

  5. Now open the CLI_test.cpp file from the Solution Explorer and provide the following code:
    1. #include "stdafx.h"  
    2.   
    3. using namespace System;  
    4.   
    5. int main(array<System::String ^> ^args)  
    6. {  
    7.     Console::WriteLine(L"Hello World");  
    8.     Console::ReadLine();  
    9.     return 0;  
    10.     }  
  6. Finally, build the project and see the output in the console.

File Create by Building the Console Application

File Create by Building

C++ / CLI Terminology

This segment intends to kick start the C++/CLI programming by outlining the essential various core C++/ CLI constructs as well as object oriented programming related and some advanced concepts of implementation, like generics, exception handling, delegates and memory management using C++ syntax under the CLR arena.

Namespace

The .NET types are organized in a special container referred to as a namespace. It can embody any types, like class, interface, structure, properties, methods and so on… We need to specify the namespace keyword after the using keyword in the header portion, if we want to reference some other assembly. We can define an alias in C++/CLI but they can only reference other namespaces, not classes.

  1. // import reference  
  2. using namespace System;  
  3. using namespace System::Text;  
  4.   
  5. //alais  
  6. using abc= System::Windows::Forms;  
  7.   
  8. // namespace definition  
  9. namespace test  
  10. {  
  11.     namespace ajay  
  12.     {  
  13.         namespace champu  
  14.              {  
  15.                     // code……  
  16.              }  
  17.     }     
  18. }  
Finally, we can't define a hierarchical namespace with one namespace statement, instead the namespace must be nested.

Class (Reference Type)

Classes are also referred to as Reference Types in C++/CLI. In C++ a class and a structure have almost the same meaning; you don't need to differentiate between a reference type and value type as you do in C# where a class typically is a reference type and a structure is a value type. In C++ a ref keyword is used to define a managed class or structure.

 

  1. //class type  
  2. public ref class testClass  
  3. {  
  4. };  
  5.   
  6. //structure type  
  7. public ref struct testStruct  
  8. {  
  9. };  
Both structures and classes are surrounded by curly braces and you must specify the semicolon at the end of the class declaration.

When confronting reference type variables, their object must be allocated on the managed heap. In C++/CLI we define the handle operator ^ in order to handle the declaration of a reference type. The gcnew operator allocates the memory on the managed heap. We can allocate space on the native heap using the new keyword.
  1. //Instantiation  
  2. testClass^ obj=gcnew testClass();  
  3.   
  4. testSruct^ obj1= gcnew testStruct();  
  5.   
  6. obj1= nullptr;  
We can de-reference or remove the corresponding space of a type from the memory by using the nullptr keyword that is similar to the C# null keyword.

Methods

The method declaration in C++/CLI is almost identical to C# as they are always defined within a class. But with one exception that the access modifier is not part of the method declaration but is written before it.
  1. public ref class testClass  
  2. {  
  3.   
  4.    public:  
  5.    void hello()  
  6.    {  
  7.    }  
  8. };  
Parameters can be passed both as a value type and as a reference type in C++/CLI. In case of reference type, we use the % operator that is almost identical to the C# ref keyword and C++ & operator.
  1. public:  
  2.       void display(int x)  
  3.     {  
  4.     }  
  5.         
  6.        void operation(int% i)  
  7.     {  
  8.     }  
  9. …………………  
  10. //Method calling  
  11.        testClass^ xyz;   
  12.        testClass^ obj=gcnew testClass();  
  13.        obj.operation(xyz);  
Constructor

A C++/CLI constructor has the same name as the class like C#. But like the method declaration the access modifier is detached from the constructor.
  1. public ref class testClass  
  2. {  
  3.   
  4. public:  
  5.     testClass(String^ a)  
  6.     {  
  7.         this->a=a;  
  8.     }  
  9. private:  
  10.     String^ a;  
  11. };  
Value Type

To declare a value type, C++/CLI uses the value keyword before the class or structure keyword. With a value type, we can allocate type space in the stack.
  1. public value class testClass  
  2. {  
  3. }  
The following table poses the predefined value type list that comes under the .NET and C++/CLI context:

value type
Enumeration

Enumeration is defined with the enum keyword in the C++/CLI language. This implementation is almost identical to other .NET languages such as C#.
  1. public enum class color  
  2. {  
  3.       RED,GREEN,BLUE,BLACK  
  4. };  
Properties

The C++/ CLI language declares properties using the property keyword and it requires a type with the get accessor and it is mandatory to define a variable value with the set accessor.
  1. public ref class testClass  
  2. {  
  3. private:  
  4.     String^ name;  
  5.   
  6. public:  
  7.     property String^ Name  
  8.     {  
  9.         String^ get()  
  10.         {  
  11.             return name;  
  12.         }  
  13.         void set()  
  14.         {  
  15.             name=value;  
  16.         }  
  17.     }  
  18. };  
Prerequisites

It is expected that the programmers must have proficiency in native C++ object oriented programming along with a deep understanding of building and executing C++ and C# applications under a .NET CLR context.

Summary

This article depicted the importance and advantages of C++/CLI over native C++ language. We came to an understanding in details of the core anatomy of C++/CLI under the CLR context. In this article, we have learned how to define the syntax of various core concepts, like value type, reference type, methods and enumerations. The next articles of these series will explain the rest of concepts such as interface, inheritance, polymorphism, loops, arrays and so on. 


Similar Articles