CLI or Common Language Infrastructure



1.1.   CLI or Common Language Infrastructure

The main purpose of CLI is to ensure the language neutral platform for application development and execution, including functions for Exception handling, Garbage Collection, security and interoperability. This is a standardized environment for the execution of the programs written in a wide range of high-level languages including Visual Basic, C#, and of course C++.
The CLI is essentially a specification for a virtual machine environment that enables applications written in diverse high - level programming languages to be executed in different system environments without the original source code ’ s being changed or replicated. The CLI specifies a standard intermediate language for the virtual machine to which the high - level language source code is compiled. With the .NET Framework, this intermediate language is referred to as Microsoft Intermediate Language (MSIL). Code in the intermediate language is ultimately mapped to machine code by a just - in - time (JIT) compiler when you execute a program. Of course, code in the CLI intermediate language can be executed within any other environment that has a CLI implementation. The CLI also defines a common set of data types called the Common Type System (CTS) that should be used for programs written in any programming language targeting a CLI implementation.

The CTS specifies how data types are used within the CLR and includes a set of predefined types. You may also define your own data types, and these must be defined in a particular way to be consistent with the CLR, as you’ll see. Having a standardized type system for representing data allows components written in different programming languages to handle data in a uniform way and makes it possible to integrate components written in different languages into a single application. Data security and program reliability is greatly enhanced by the CLR, in part because dynamic memory allocation and release for data is fully automatic, but also because the MSIL code for a program is comprehensively checked and validated before the program executes. The CLR is just one implementation of the CLI specification that executes under Microsoft Windows on a PC; there will undoubtedly be other implementations of the CLI for other operating system environments and hardware platforms. You’ll sometimes find that the terms CLI and CLR are used interchangeably, although it should be evident that they are not the same thing. The CLI is a standard specification; the CLR is Microsoft’s implementation of the CLI.

1.2.   Writing C++ Application

You have tremendous flexibility in the types of applications and program components that you can develop with Visual C++ 2010. As noted earlier in this chapter, you have two basic 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 executes natively. For window – based applications targeting the CLR, you use Windows Forms as the base for the GUI provided by the .NET Framework libraries. Using Windows Forms enables rapid GUI development because you assemble the GUI graphically from standard components and have the code generated completely automatically. You then just need to customize the code that has been generated to provide the functionality that you require. For natively executing code, you have several ways to go. One possibility is to use the Microsoft Foundation Classes (MFC) for programming the graphical user interface for your Windows application. The MFC encapsulates the Windows operating system Application Programming Interface (API) for GUI creation and control and greatly eases the process of program development. The Windows API originated long before the C++ language arrived on the scene, so it has none of the object - oriented characteristics that would be expected if it were written today; however, you are not obliged to use the MFC. If you want the ultimate in performance, you can write your C++ code to access the Windows API directly. C++ code that executes with the CLR is described as managed C++ because data and code are managed by the CLR. In CLR programs, the release of memory that you have allocated dynamically for storing data is taken care of automatically, thus eliminating a common source of error in native C++ applications. C++ code that executes outside the CLR is sometimes described by Microsoft as unmanaged C++ because the CLR is not involved in its execution. With unmanaged C++ you must take care of all aspects of allocating and releasing memory during execution of your program yourself, and also forego the enhanced security provided by the CLR. You’ll also see unmanaged C++ referred to as native C++ because it compiles directly to native machine code.
Figure 1 - 1 is not the whole story. An application can consist partly of managed C++ and partly of native C++, so you are not obliged to stick to one environment or the other. Of course, you do lose out somewhat by mixing code, so you would choose to follow this approach only when necessary, such as when you want to convert an existing native C++ application to run with the CLR. You obviously won’t get the benefits inherent in managed C++ in the native C++ code, and there can also be appreciable overhead involved in communications between the managed and unmanaged code components. The ability to mix managed and unmanaged code can be invaluable, however, when you need to develop or extend existing unmanaged code but also want to obtain the advantages of using the CLR. Of course, for new applications you should decide at the outset whether you want to create a managed C++ application or a native C++ application.

1.3.   Learning Windows Programming

There are always two basic aspects to interactive applications executing under Windows: You need code to create the graphical user interface (GUI) with which the user interacts, and you need code to process these interactions to provide the functionality of the application. Visual C++ 2010 provides you with a great deal of assistance in both aspects of Windows application development. As you ’ ll see later in this chapter, you can create a working Windows program with a GUI without writing any code yourself at all. All the basic code to create the GUI can be generated automatically by Visual C++ 2010; however, it ’ s essential to understand how this automatically generated code works because you need to extend and modify it to make it do what you want, and to do that you need a comprehensive understanding of C++. For this reason you ’ ll fi rst learn C++ — both the native C++ and C++/CLI versions of the language — without getting involved in Windows programming considerations. After you ’ re comfortable with C++
you ’ ll learn how to develop fully - fl edged Windows applications using native C++ and C++/CLI. This means that while you are learning C++, you ’ ll be working with programs that involve only command line input and output. By sticking to this rather limited input and output capability, you ’ ll be able to concentrate on the specifics of how the C++ language works and avoid the inevitable complications involved in GUI building and control. After you become comfortable with C++ you ’ ll fi nd that it ’ s an easy and natural progression to applying C++ to the development of Windows application programs.

1.3.1.                 Learning C++

Visual C++ 2010 fully supports two versions of C++, defi ned by two separate standards:
·         The ISO/IEC C++ standard is for implementing native applications — unmanaged C++. This version of C++ is supported on the majority of computer platforms.
·         The C++/CLI standard is designed specifi cally for writing programs that target the CLR and is an extension of the ISO/IEC C++.
Because C++/CLI is an extension of ISO/IEC C++, the first part of each chapter introduces elements of the ISO/IEC C++ language; the second part explains the additional features that C++/CLI introduces. Writing programs in C++/CLI enables you to take full advantage of the capabilities of the .NET Framework, something that is not possible with programs written in ISO/IEC C++. Although C++/CLI is an extension of ISO/IEC C++, to be able to execute your program fully with the CLR means that it must conform to the requirements of the CLR. This implies that there are some features of ISO/IEC C++ that you cannot use in your CLR programs. One example of this that you might deduce from what I have said up to now is that the dynamic memory allocation and release facilities offered by ISO/IEC C++ are not compatible with the CLR; you must use the CLR mechanism for memory management, and this implies that you must use C++/CLI classes, not native C++ classes.

1.3.2.                 The C++ Standards

At the time of writing, the currently approved C++ language standard is defi ned by the document ISO/IEC 14882:1998, published by the International Organization for Standardization (ISO). This is the well - established version of C++ that has been around since 1998 and is supported by compilers on the majority of computer hardware platforms and operating systems. There is a new standard for C++ in draft form that is expected to be approved in the near future. Visual C++ 2010 already supports several of the new language capabilities offered by this new standard, and these are described in this book.
Programs that you write in standard C++ can be ported from one system environment to another
reasonably easily, although the library functions that a program uses — particularly those related to building a graphical user interface — are a major determinant of how easy or difficult it will be. ISO/IEC standard C++ is the first choice of many professional program developers because it is so widely supported, and because it is one of the most powerful programming languages available today.
C++/CLI is a version of C++ that extends the ISO/IEC standard for C++ to better support the Common Language Infrastructure (CLI) defined by the standard ECMA - 355. The C++/CLI language specification is defined by the standard ECMA - 372 and is available for download from the ECMA web site. This standard was developed from an initial technical specification that was produced by Microsoft to support the execution of C++ programs with the .NET Framework. Thus, both the CLI and C++/CLI were originated by Microsoft in support of the .NET Framework. Of course, standardizing the CLI and C++/CLI greatly increases the likelihood of implementation in environments other than Windows. It ’ s important to appreciate that although C++/CLI is an extension of ISO/IEC C++, there are features of ISO/IEC C++ that you must not use when you want your program to execute fully under the control of the CLR. You ’ ll learn what these are as you progress through the book.
The CLR offers substantial advantages over the native environment. If you target your C++ programs at the CLR, they will be more secure and not prone to the potential errors you can make when using the full power of ISO/IEC C++. The CLR also removes the incompatibilities introduced by various high - level languages by standardizing the target environment to which they are compiled, and thus permits modules written in C++ to be combined with modules written in other languages, such as C# or Visual Basic.

1.3.3.                 Attributes

Attributes are an advanced feature of programming with C++/CLI that enables you to add descriptive declarations to your code. At the simplest level, you can use attributes to annotate particular programming elements in your program, but there’s more to attributes than just additional descriptive data. Attributes can affect how your code behaves at run time by modifying the way the code is compiled or by causing extra code to be generated that supports additional capabilities. A range of standard attributes is available for C++/CLI, and it is also possible to create your own.


1.3.4.                 Console Applications
As well as developing Windows applications, Visual C++ 2010 also enables you to write, compile, and test C++ programs that have none of the baggage required for Windows programs — that is, applications that are essentially character - based, and command - line programs. These programs are called console applications in Visual C++ 2010 because you communicate with them through the keyboard and the screen in character mode.
When you write console applications it might seem as if you are being sidetracked from the main
Objective of Windows programming, but when it comes to learning C++ (which you do need to
do before embarking on Windows - specific programming) it’s the best way to proceed. There’s a lot of code in even a simple Windows program, and it’s very important not to be distracted by the complexities of Windows when learning the ins and outs of C++. Therefore, in the early chapters of the book, which are concerned with how C++ works, you’ll spend time walking with a few lightweight console applications before you get to run with the heavyweight sacks of code in the world of Windows.
While you’re learning C++, you’ll be able to concentrate on the language features without worrying about the environment in which you’re operating. With the console applications that you’ll write, you have only a text interface, but this will be quite sufficient for understanding all of C++ because there ’ s no graphical capability within the definition of the language. Naturally, I will provide extensive coverage of graphical user interface programming when you come to write programs specifically for Windows using Microsoft Foundation Classes (MFC) in native C++ applications, and Windows Forms with the CLR.

There are two distinct kinds of console applications, and you’ll be using both.
·         Win32 console applications compile to native code. You’ll be using these to try out the capabilities of ISO/IEC C++.
·         CLR console applications target the CLR. You’ll be using these when you are working with the features of C++/CLI.

1.3.5.                 Windows Programming Concepts

The project creation facilities provided with Visual C++ 2010 can generate skeleton code for a wide variety of native C++ application programs automatically, including basic Windows programs. For Windows applications that you develop for the CLR you get even more automatic code generation. You can create complete applications using Windows Forms that require only a small amount of customized code to be written by you, and some that require no additional code at all. Creating a project is the starting point for all applications and components that you develop with Visual C++2010, and to get a flavor of how this works you ’ ll look at the mechanics of creating some examples, including an outline Windows program, later in this chapter.
A Windows program, whether a native C++ program or a program written for the CLR, has a different structure from that of the typical console program you execute from the command line, and it ’ s more complicated. In a console program you can get input from the keyboard and write output back to the command line directly, whereas a Windows program can access the input and output facilities of the computer only by way of functions supplied by the host environment; no direct access to the hardware resources is permitted. Because several programs can be active at one time under Windows, Windows has to determine which application a given raw input, such as a mouse click or the pressing of a key on the keyboard, is destined for, and signal the program concerned accordingly. Thus, the Windows operating system has primary control of all communications with the user. The nature of the interface between a user and a Windows application is such that a wide range of different inputs is usually possible at any given time. A user may select any of a number of menu options, click a toolbar button, or click the mouse somewhere in the application window. A well - designed Windows application has to be prepared to deal with any of the possible types of input at any time because there is no way of knowing in advance which type of input is going to occur. These user actions are received by the operating system in the fi rst instance, and are all regarded by Windows as events. An event that originates with the user interface for your application will typically result in a particular piece of your program code being executed. How program execution proceeds is therefore determined by the sequence of user actions. Programs that operate in this way are referred to as event - driven programs , and are different from traditional procedural programs that have a single order of execution. Input to a procedural program is controlled by the program code and can occur only when the program permits it; therefore, a Windows program consists primarily of pieces of code that respond to events caused by the action of the user, or by Windows itself. This sort of program structure is illustrated in Figure 1 - 2.

Each square block in Figure 1 - 2 represents a piece of code written specifically to deal with a particular event. The program may appear to be somewhat fragmented because of the number of disjointed blocks of code, but the primary factor welding the program into a whole is the Windows operating system itself. You can think of your program as customizing Windows to provide a particular set of capabilities. Of course, the modules servicing various external events, such as the selection of a menu or a mouse click, all typically have access to a common set of application - specific data in a particular program.
This application data contains information that relates to what the program is about — for example, blocks of text recording scoring records for a player in a program aimed at tracking how your baseball team is doing — as well as information about some of the events that have occurred during execution of the program. This shared collection of data allows various parts of the program that look independent to communicate and operate in a coordinated and integrated fashion. I will go into this in much more detail later in the book. Even an elementary Windows program involves several lines of code, and with Windows programs generated by the application wizards that come with Visual C++ 2010, “ several ” turns out to be “ many. ” To simplify the process of understanding how C++ works, you need a context that is as uncomplicated as possible. Fortunately, Visual C++ 2010 comes with an environment that is ready - made for the purpose.

1.3.6.                 WHAT IS THE INTEGRATED DEVELOPMENT ENVIRONMENT?

The integrated development environment (IDE) that comes with Visual C++ 2010 is a completely self - contained environment for creating, compiling, linking, and testing your C++ programs. It also happens to be a great environment in which to learn C++ (particularly when combined with a great book).
Visual C++ 2010 incorporates a range of fully integrated tools designed to make the whole process of writing C++ programs easy. You will see something of these in this chapter, but rather than grind through a boring litany of features and options in the abstract, you can first take a look at the basics to get a view of how the IDE works, and then pick up the rest in context as you
go along. The fundamental parts of Visual C++ 2010, provided as part of the IDE, are the editor, the compiler, the linker, and the libraries. These are the basic tools that are essential to writing and executing a C++ program. Their functions are as follows.

1.3.7.                 The Editor

The editor provides an interactive environment in which to create and edit C++ source code. As well as the usual facilities, such as cut and paste, which you are certainly already familiar with, the editor also provides color cues to differentiate between various language elements. The editor automatically recognizes fundamental words in the C++ language and assigns a color to them according to what they are. This not only helps to make your code more readable, but also provides a clear indicator of when you make errors in keying such words.

1.3.8.                 The Compiler
The compiler converts your source code into object code, and detects and reports errors in the compilation process. The compiler can detect a wide range of errors caused by invalid or unrecognized program code, as well as structural errors, such as parts of a program that can never be executed. The object code output from the compiler is stored in fi les called object fi les that have names with the extension .obj.

1.3.9.                 The Linker

The linker combines the various modules generated by the compiler from source code fi les, adds required code modules from program libraries supplied as part of C++, and welds everything into an executable whole. The linker can also detect and report errors — for example, if part of your program is missing, or a nonexistent library component is referenced.

1.3.10.             The Libraries

A library is simply a collection of prewritten routines that supports and extends the C++ language by providing standard professionally-produced code units that you can incorporate into your programs to carry out common operations. The operations implemented by routines in the various libraries provided by Visual C++ 2010 greatly enhance productivity by saving you the effort of writing and testing the code for such operations yourself. I have already mentioned the .NET Framework library, and there are a number of others — too many to enumerate here — but I’ll identify the most important ones. The Standard C++ Library defines a basic set of routines common to all ISO/IEC C++ compilers. It contains a wide range of routines, including numerical functions, such as the calculation of square roots and the evaluation of trigonometrical functions; character - and string – processing routines, such as the classification of characters and the comparison of character strings; and many others. You’ll get to know quite a number of these as you develop your knowledge of
ISO/IEC C++. There are also libraries that support the C++/CLI extensions to ISO/IEC C++. Native window - based applications are supported by a library called the Microsoft Foundation Classes (MFC). The MFC greatly reduces the effort needed to build the graphical user interface for an application. (You’ll see a lot more of the MFC when you finish exploring the nuances of the C++ language.) Another library contains a set of facilities called Windows Forms, which are roughly the equivalent of the MFC for Windows - based applications executed with the .NET Framework. You’ll be seeing how you make use of Windows Forms to develop applications, too.

1.3.11.             USING THE IDE

All program development and execution in this book is performed from within the IDE. When you start Visual C++ 2010 you’ll notice an application window similar to that shown in
Figure 1 - 3.
The pane to the left in Figure 1 - 3 is the Solution Explorer window, the top right pane presently showing the Start page is the Editor window, and the tab visible in the pane at the bottom is the Output window. The Solution Explorer window enables you to navigate through your program fi les and display their contents in the Editor window, and to add new fi les to your program. The Solution Explorer window has an additional tab (only three are shown in Figure 1 - 3) that displays the Resource View for your application, and you can select which tabs are to be displayed from the View menu. The Editor window is where you enter and modify source code and other components of your application. The Output window displays the output from build operations in which a project is compiled and linked. You can choose to display other windows by selecting from the View menu. Note that a window can generally be undocked from its position in the Visual C++application window. Just right - click the title bar of the window you want to undock and select Float from the pop - up menu. In general, I will show windows in their undocked state in the book. You can restore a window to its docked state by right - clicking its title bar and selecting Dock from the pop - up.

1.3.12.             Toolbar Options

You can choose which toolbars are displayed in your Visual C++window by right - clicking in the toolbar area. The range of toolbars in the list depends on which edition of Visual C++ 2010 you have installed. A pop - up menu with a list of toolbars (Figure 1 - 4)appears, and the toolbars currently displayed have checkmarks alongside them. This is where you decide which toolbars are visible at any one time. You can make your set of toolbars the same as those shown in Figure 1 - 3 by making sure the Build, Class Designer, Debug, Standard, and View Designer menu items are checked. Clicking a toolbar in the list checks it if it is unchecked, and results in its being displayed; clicking a toolbar that is checked unchecks it and hides the toolbar.
You don’t need to clutter up the application window with all the toolbars you think you might need at some time. Some toolbars appear automatically when required, so you’ll probably find that the default toolbar selections are perfectly adequate most of the time. As you develop your applications, from time to time you might think it would be more convenient to have access to toolbars that aren’t displayed. You can change the set of visible toolbars whenever it suits you by right - clicking in the toolbar area and choosing from the context menu.
NOTE As in many other Windows applications, the toolbars that make up Visual C++ 2010 come complete with tooltips. Just let the mouse pointer linger over a toolbar button for a second or two, and a white label will display the function of that button.

1.3.13.             Dockable Toolbars

A dockable toolbar is one that you can move around to position it at a convenient place in the window. You can arrange for any of the toolbars to be docked at any of the four sides of the application window. If you right - click in the toolbar area and select Customize from the pop - up, the Customize dialog will be displayed. You can choose where a particular toolbar is docked by selecting it and clicking the Modify Selection button. You can then choose from the drop - down list to dock the toolbar where you want. Figure 1 - 5 shows how the dialog looks after the user selects the Build toolbar on the left and clicks the Modify Selection button. You’ll recognize many of the toolbar icons that Visual C++ 2010 uses from other Windows applications, but you may not appreciate exactly what these icons do in the context of Visual C++, so I’ll describe them as we use them. Because you’ll use a new project for every program you develop, looking at what exactly a project is and understanding how the mechanism for defining a project works is a good place to start finding out about Visual C++ 2010.

1.3.14.             Documentation

There will be plenty of occasions when you’ll want to find out more information about Visual C++ 2010 and its features and options. Press Ctrl+Alt+F1 to access the product documentation. The Help menu also provides various routes into the documentation, as well as access to program samples and technical support.

1.3.15.             Projects and Solutions

A project is a container for all the things that make up a program of some kind — it might be a
console program, a window - based program, or some other kind of program — and it usually consists of one or more source fi les containing your code, plus possibly other fi les containing auxiliary data. All the fi les for a project are stored in the project folder; detailed information about the project is stored in an XML fi le with the extension .vcxproj , also in the project folder. The project folder also contains other folders that are used to store the output from compiling and linking your project.
The idea of a solution is expressed by its name, in that it is a mechanism for bringing together all the programs and other resources that represent a solution to a particular data - processing problem.
For example, a distributed order - entry system for a business operation might be composed of several different programs that could each be developed as a project within a single solution; therefore, a solution is a folder in which all the information relating to one or more projects is stored, and one or more project folders are subfolders of the solution folder. Information about the projects in a solution is stored in two fi les with the extensions .sln and .suo, respectively. When you create a project anew solution is created automatically unless you elect to add the project to an existing solution. When you create a project along with a solution, you can add further projects to the same solution. You can add any kind of project to an existing solution, but you will usually add only a project related in some way to the existing project, or projects, in the solution. Generally, unless you have a good reason to do otherwise, each of your projects should have its own solution. Each example you create with this book will be a single project within its own solution.
Defining a Project The first step in writing a Visual C++ 2010 program is to create a project for it using the File New Project menu option from the main menu or by pressing Ctrl+Shift+N ; you can also simply click New Project . . . on the Start page. As well as containing fi les that define all the code and any other data that makes up your program, the project XML fi le in the project folder also records the Visual C++ 2010 options you ’ re using. That’s enough introductory stuff for the moment. It’s time to get your hands dirty.
Share on Google Plus