Digital forensics

Managed C++/CLI Programming: Part-1

Ajay Yadav
October 3, 2013 by
Ajay Yadav

Abstract

This article illustrates the theory and principle behind C++/CLI programming in a .NET CLR context. We shall investigate the remarkable features of C++/CLI programming, for instance its advantage over native C++ language with a CLR context. We'll run through the basic mechanism to create and executed CLR console and other application prototypes with the help of Visual Studio 2010. We'll also explore the semantics of C++/CLI language in order to write and implement code. This segment also covers various significant aspects of a CLR C++ programming prototype in detail, regarding hardcore object oriented programming.

Learn Digital Forensics

Learn Digital Forensics

Build your skills with hands-on forensics training for computers, mobile devices, networks and more.

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, and 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 a standardized environment for the execution of programs written in a wide range of high level languages including C#, VB and C++. The specification of CLR is now embodied in the ECMA standard for CLI (Common Language Infrastructure). That's why C++ for the CLR is referred to as C++/CLI.

CLI is essentially a specification for a virtual machine environment that enables applications written in other high-level languages to be executed in different system environments without recompiling 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've noted earlier, you have two options for Windows applications; you can write code that executes with the CLR, or you could also write code that compiles directly to machine code, thus executed natively. C++ code that executes with the CLR is described as managed C++ because data and code is managed by the CLR. It may release memory that you've allocated dynamically for storing data, automatically. This eliminates 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++. With unmanaged C++, you must take care of all aspects of allocating and releasing memory during execution of your program yourself. Also you have to shield your application from various security penetration breaches.

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 in 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 the C+/CLI programming language, by using the Visual studio 2010. Although, this would the simplest logic implementation, we're just trying to display a string value by a CLR console based application as in other C# console based applications. Here are the tutorial steps;

  1. First, make sure that the VC++ plugin is properly configured in Visual Studio 2010. If not, then re-install the software and during that process choose the VC++ options.
  2. Open Visual Studio 2010. Go to the File Menu, select New Project and you will find the VC++ language plugin in the dialog box's left pane.
  3. Expand the VC++ and select CLR. Then, choose CLR console application from the right pane.
  4. Finally get a name to project like "CLI_test" and finally hit OK as per the above figure.
  5. Now open the CLI_test.cpp file from the solution explorer and enter this code;
    [c]#include "stdafx.h"

    using namespace System;

    int main(array<System::String ^> ^args)

    {

    Console::WriteLine(L"Hello World");

    Console::ReadLine();

    return 0;

    }

    [/c]

  6. Finally, build the project and see the output in the console.

File Create by Building the Console Application

Files Extension Description

.exe This is the executable file for the program.

.obj Compile produces these objects files containing machine code from your program source files.

.ilk Such files used by linker when you rebuild your project.

.pch This is the pre-compiled header file.

.idb They contain information that used when we rebuild the application.

.pdb It contains debugging information that is used when we execute the program in debug mode.

C++ / CLI Terminology

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

Namespace

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

[c]

// import reference

using namespace System;

using namespace System::Text;

//alais
using abc= System::Windows::Forms;

// namespace definition

namespace test

{

namespace ajay

{

namespace champu

{

// code……

}

}

}

[/c]

Finally, we can't define hierarchical namespace with one namespace statement; instead the namespace must be nested.

Class (Reference Type)

Classes are also referred to as Reference Type in C++/CLI. A class and structure have almost the same meaning; you don't have to separate between reference type and value type as you do with in C#. Class, typically, comes under reference type, and structure is part of value type. In C++ a ref keyword is used to define a managed class or structure.

[c]

//class type

public ref class testClass

{

};

//structure type

public ref struct testStruct

{

};

[/c]

Both structure and class are surrounded by curly braces and you must have to specify the semicolon at the end of the class declaration.

When confronting with 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 reference type. The gcnew operator allocates the memory on the managed heap. We can allocate space on the native heap by using the new keyword.

[c]

//Instantiation

testClass^ obj=gcnew testClass();

testSruct^ obj1= gcnew testStruct();

obj1= nullptr;
[/c]

We can de-reference or remove the corresponding space of a type from the memory by using the nullptr keyword, which is similar to 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 the exception that the access modifier is not part of the method declaration, but is written before it.

[c]

public ref class testClass

{

public:

void hello()

{

}

};

[/c]

Parameters can passed both value type and reference type in C++/CLI. In the case of reference type, we used the % operator which is almost identical to C# ref keyword and C++ & operator.

[c]

public:

void display(int x)

{

}

void operation(int% i)

{

}

…………………

//Method calling

testClass^ xyz;

testClass^ obj=gcnew testClass();

obj.operation(xyz);

[/c]

Constructor

C++/CLI constructor has the same name as the class, like C#. But as like method declaration access modifier is detached from the constructor.

[c]

public ref class testClass

{

public:

testClass(String^ a)

{

this->a=a;

}

private:

String^ a;

};

[/c]

Value Type

To declare a value type, C++/CLI uses the value keyword before the class or structure keyword. With value type, we can allocate type space in stack.

[c]

public value class testClass

{

}

[/c]

The following table poses the predefine value type list that comes under .NET and C++/CLI;

C++/CLI type Size(Bytes) .NET Types

wchar_t 2 Char

bool 1 (true, false) Boolean

short 2 Int16

int 4 Int32

long long 8 Int64

ushort 2 UInt16

unsigned int 4 UInt32

unsigned long long 8 UInt64

Enumeration

Enumeration is defined with the enum keyword in C++/CLI language. This implementation is almost identical to other .NET languages such as C#.

[c]

public enum class color

{

RED,GREEN,BLUE,BLACK

};

[/c]

Properties

The C++/ CLI language declares the properties using the property keyword and it requires a type with the get parameter and mandatory to define a variable value with the set parameter.

[c]

public ref class testClass

{

private:

String^ name;

public:

property String^ Name

{

String^ get()

{

return name;

}

void set()

{

name=value;

}

}

};

[/c]

Prerequisites

It's 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 .NET CLR.

Summary

Learn Digital Forensics

Learn Digital Forensics

Build your skills with hands-on forensics training for computers, mobile devices, networks and more.

This article depicted the importance and advantage of C++/CLI over native C++ language. We came to understanding in detail about the core anatomy of C++/CLI under CLR context. In this article, we've learned how to define the syntax of various core concepts like value type, reference type, methods, and enumerations. The next articles in this series will explain the rest of concepts such as interface, inheritance, polymorphism, loops, array, etc.

Ajay Yadav
Ajay Yadav

Ajay Yadav is an author, Cyber Security Specialist, SME, Software Engineer, and System Programmer with more than eight years of work experience. He earned a Master and Bachelor Degree in Computer Science, along with abundant premier professional certifications. For several years, he has been researching Reverse Engineering, Secure Source Coding, Advance Software Debugging, Vulnerability Assessment, System Programming and Exploit Development.

He is a regular contributor to programming journal and assistance developer community with blogs, research articles, tutorials, training material and books on sophisticated technology. His spare time activity includes tourism, movies and meditation. He can be reached at om.ajay007[at]gmail[dot]com