Appendix G: Writing Managed C++ Code for the.net Framework

Similar documents
UNIT 1. Introduction to Microsoft.NET framework and Basics of VB.Net

C#.Net. Course Contents. Course contents VT BizTalk. No exam, but laborations

.Net Technologies. Components of.net Framework

Question And Answer.

Darshan Institute of Engineering & Technology for Diploma Studies

Chapter 1 Getting Started

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Motivation was to facilitate development of systems software, especially OS development.

Motivation was to facilitate development of systems software, especially OS development.

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Understand Computer Storage and Data Types

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

Pointers II. Class 31

Chapter 12 Microsoft Assemblies. Software Architecture Microsoft Assemblies 1

Department of Computer Applications

C++\CLI. Jim Fawcett CSE687-OnLine Object Oriented Design Summer 2017

New programming language introduced by Microsoft contained in its.net technology Uses many of the best features of C++, Java, Visual Basic, and other

Chapter 1 GETTING STARTED. SYS-ED/ Computer Education Techniques, Inc.

Chapter 2: Using Data

a data type is Types

Module 2: Introduction to a Managed Execution Environment

CSc Introduction to Computing

Lecture 2 Tao Wang 1

Classes - 2. Data Processing Course, I. Hrivnacova, IPN Orsay

Variables. Data Types.

Fig 1.1.NET Framework Architecture Block Diagram

Introduction to.net Framework

REVIEW. The C++ Programming Language. CS 151 Review #2

A First Program - Greeting.cpp

Chapter 1 INTRODUCTION SYS-ED/ COMPUTER EDUCATION TECHNIQUES, INC.

Computer Programming : C++

CS242 COMPUTER PROGRAMMING

PES INSTITUTE OF TECHNOLOGY

Zheng-Liang Lu Java Programming 45 / 79

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

C++ Data Types. 1 Simple C++ Data Types 2. 3 Numeric Types Integers (whole numbers) Decimal Numbers... 5

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

Chapter 2. C++ Syntax and Semantics, and the Program Development Process. Dale/Weems 1

DAD Lab. 1 Introduc7on to C#

Introduction to.net Framework Week 1. Tahir Nawaz

Lab # 02. Basic Elements of C++ _ Part1

UNIT I An overview of Programming models Programmers Perspective

C# MOCK TEST C# MOCK TEST I

Computers and Programming Section 450. Lab #1 C# Basic. Student ID Name Signature

C++ Programming: From Problem Analysis to Program Design, Third Edition

LECTURE 02 INTRODUCTION TO C++

Exercise: Inventing Language

Introduction To C#.NET

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Fundamental C# Programming

Outline. Review of Last Week II. Review of Last Week. Computer Memory. Review Variables and Memory. February 7, Data Types

Java Identifiers, Data Types & Variables

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Introduction to C# Applications

Chapter 2: Introduction to C++

Scope. Scope is such an important thing that we ll review what we know about scope now:

A Comparison of Visual Basic.NET and C#

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Tokens, Expressions and Control Structures

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

BASIC ELEMENTS OF A COMPUTER PROGRAM

Bit (0, 1) Byte (8 bits: 0-255) Numeral systems. Binary (bin) 0,1 Decimal (dec) 0, 1, 2, 3, Hexadecimal (hex) 0, 1, 2, 3, 1/13/2011

Introduce C# as Object Oriented programming language. Explain, tokens,

Assumptions. History

Visual C# Instructor s Manual Table of Contents

6.096 Introduction to C++ January (IAP) 2009

IT 1033: Fundamentals of Programming Data types & variables

CS201 - Introduction to Programming Glossary By

Variables and numeric types

Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

Creating a C++ Program

Introducing C# After this discussion, we'll move on to a simple description of C# itself, including its origins and similarities to C++.

Introduction. In this preliminary chapter, we introduce a couple of topics we ll be using DEVELOPING CLASSES

Week 3 Lecture 2. Types Constants and Variables

CHAPTER 7 OBJECTS AND CLASSES

2. A GUI A. uses buttons, menus, and icons B. should be easy for a user to manipulate C. both (a) and (b) D. stands for Graphic Use Interaction

Introduction to the C++ Programming Language

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

Implementing an ADT with a Class

6. Pointers, Structs, and Arrays. 1. Juli 2011

Short Notes of CS201

CS 2150 Exam 1, Spring 2018 Page 1 of 6 UVa userid:

6. Pointers, Structs, and Arrays. March 14 & 15, 2011

Chapter 2. Procedural Programming

Review for COSC 120 8/31/2017. Review for COSC 120 Computer Systems. Review for COSC 120 Computer Structure

EMBEDDED SYSTEMS PROGRAMMING Language Basics

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Managing Memory. (and low level Data Structures) Lectures 22, 23. Hartmut Kaiser.

LESSON 2 VARIABLES, OPERATORS, EXPRESSIONS, AND USER INPUT

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

Types, Values, Variables & Assignment. EECS 211 Winter 2018

Unit 1: Visual Basic.NET and the.net Framework

! A literal represents a constant value used in a. ! Numbers: 0, 34, , -1.8e12, etc. ! Characters: 'A', 'z', '!', '5', etc.

Transcription:

Appendix G: Writing Managed C++ Code for the.net Framework What Is.NET?.NET is a powerful object-oriented computing platform designed by Microsoft. In addition to providing traditional software development tools, it provides technologies to create Internet-based programs, and programs that provide services over the Web..NET consists of several layers of software that sit above the operating system and provide a managed environment in which programs can execute. Within this environment,.net manages a program s memory allocation and destruction needs, resource usage, and security. For software developers,.net consists of the following important components: The Common Language Runtime (CLR) The Common Type System (CTS) The.NET Framework Class Library Let s briefly look at each of these. The Common Language Runtime The Common Language Runtime, or CLR, is the part of.net that actually runs application code. The CLR is a managed runtime environment. This means that the CLR executes code within an environment where memory allocation and de-allocation, security, and type compatibility are strictly managed. 1

2 Appendix G: Writing Managed C++ Code for the.net Framework Table G-1 The Common Type System The Common Type System or CTS is a set of common data types provided by.net. These data types are available to all applications running in the CLR, and they have the same characteristics regardless of the programming language used. In C++, the standard primitive data types all correspond directly to a.net type. For example,.net provides a data type named Int32, which is a 32-bit integer. In C++, the int data type corresponds to Int32. Table G-1 shows a list of the.net common types, as well as the C++ types that they correspond to. Note that C++ does not provide primitive types for all of the.net types..net Common Types.NET Common Type Description Equivalent C++ Type Byte 8-bit unsigned integer char SByte 8 bit signed integer signed char Boolean 8-bit Boolean value (true or false) bool Char 16-bit Unicode character wchar_t Int16 16-bit signed integer short Int32 32-bit signed integer int long Int64 64-bit signed integer _int64 UInt16 16-bit unsigned integer unsigned short UInt32 32-bit unsigned integer unsigned int unsigned long UInt64 64-bit unsigned integer unsigned _int64 Single 32-bit single precision floating point float Double 64-bit double precision floating point double Decimal 96-bit floating point value with 28 significant digits None IntPtr UIntPtr A signed integer used as a pointer. The size is platformspecific An unsigned integer used as a pointer. The size is platform-specific None None The.NET Framework Class Library The.NET Framework Class Library is a library of object-oriented types, such as classes and structures, which provide access to the capabilities of.net. Programmers may use these object-oriented types to create managed applications that run within the CLR. In

Appendix G: Writing Managed C++ Code for the.net Framework 3 addition, many of the.net Framework classes may be used as base classes. This allows programmers to create specialized classes that serve specific needs within an application. Microsoft Intermediate Language In order for a program to execute, its high-level language source code must be converted to some type of executable code. Traditional compilers translate source code into binary executable code, which may be run directly by the CPU. In order for a program to be run by the CLR, however, it is not compiled to binary executable code. Instead, it must be translated into Microsoft Intermediate Language, or MSIL. MSIL code is called "intermediate" because it represents an intermediate step between source code and executable code. When a.net program runs, the CLR reads its MSIL code, then just before execution, converts the MSIL code to binary executable code. The part of the CLR that converts MSIL into binary executable code is called the Just-In-Time compiler or JIT compiler. Figure G-1 illustrates the process of compiling and executing a.net program. NOTE: The JIT compiler doesn t necessarily translate an entire program all at once to executable code. It usually compiles parts of the program as they are needed. The conversion of source code to MSIL might seem like an unnecessary step, but it has some advantages. First, because all.net programs are compiled to MSIL, it makes it easier to mix code from several different languages in the same application. Second, because MSIL is not specific to any particular hardware platform, it is portable to any system that supports the CLR. Managed Code A program may be executed by the CLR if it is written in a language that conforms to the Common Language Specification, or CLS. The CLS is a set of standards that compiler and programming language designers must follow if they wish for programs written in their language to run in the.net environment. In Visual Studio.NET, Microsoft provides the C#, Visual Basic.NET, and Visual J# languages, all of which can be used to write CLS compliant code. A Visual C++ compiler is also provided. However, standard C++ does not produce code that can be managed by the CLR, even if it is written and compiled with Visual C++. To bridge the gap between unmanaged C++ code and the.net CLR, Microsoft provides extensions to the C++ language which you may use to generate CLS compliant code. C++ code that is written with these extensions is known as managed C++ code because it may be executed in and managed by the CLR. To demonstrate how to write managed C++ code, we will look at two examples: managed dynamic arrays, and managed classes.

4 Appendix G: Writing Managed C++ Code for the.net Framework Figure G-1 Source File 1 The.NET compiler translates the source code file into MSIL code..net Compiler MSIL code 2 The CLR invokes the Just-In-Time compiler to translate the MSIL code to binary executable code. JIT compiler Executable code 3 The program executes. Program execution

Appendix G: Writing Managed C++ Code for the.net Framework 5 Managed Dynamic Arrays In standard C++, the programmer must be careful to free the memory used by dynamically allocated objects. For example, look at the following code: const int SIZE = 12; int *numbers = new int[size]; This code dynamically allocates enough memory for an array of twelve integers, and assigns the starting address of the array to the numbers pointer. When the program is finished using the array, it should execute the following code to free the memory used by the array: delete [] numbers; In an unmanaged runtime environment, failure to properly reclaim dynamically allocated memory can lead to serious problems. One such problem is known as a memory leak. This is when a program repeatedly allocates memory but never frees it. Eventually, the available memory will run out. Another problem occurs when a dynamically allocated object is destroyed, but other code in the program continues to use the object as though it were still in memory. Because the CLR is a managed runtime environment, it performs automatic garbage collection. This means that it automatically frees the memory used by dynamically allocated objects when they are no longer referenced by any part of the program. The programmer no longer has to worry about using delete to free memory. For example, suppose a function in a managed C++ program dynamically allocates an array, and the starting address of the array is stored in a local variable. When the function terminates, the local variable goes out of scope. The dynamically allocated array is no longer referenced by any variables, so the runtime environment will automatically free the memory that it uses. In Microsoft Visual C++, the syntax for creating a managed dynamic array is different from the syntax that you normally use. Look at the following example: // Create an array of integers. const int SIZE = 12; int numbers gc[] = new int gc[size]; // Store some values in the array. for (int i = 0; i < SIZE; i++) numbers[i] = i; In this example the third line of code creates a managed array of 12 integers. Notice the use of gc in that line of code. (That s two underscores followed by gc.) The gc key word is part of Microsoft s managed extensions for C++. It allows you to dynamically allocate arrays (as well as other objects) which are managed by the CLR. When the array is no longer referenced by any variable, the CLR s garbage collector will free the memory it uses.

6 Appendix G: Writing Managed C++ Code for the.net Framework NOTE: The garbage collector runs in the background. Under normal circumstances it runs infrequently, allowing more important tasks to operate. If available memory becomes low, however, it will run more frequently. With this in mind, you cannot predict exactly when a dynamically allocated array or object will be deleted. Managed Classes In a class declaration you can place the gc key word before the class key word to create a managed class. (As previously mentioned, that s two underscores followed by gc.) When an instance of a managed class is allocated in memory, the CLR will automatically free it from memory when it is no longer referenced by any variables. Here is an example of a managed class declaration: gc class Circle { private: double radius; public: Circle(double rad) { radius = rad; } }; double getradius() { return radius; } double getarea() { return 3.14159 * radius * radius; } An instance of the class can then be dynamically allocated in memory, as shown here: Circle *c = new Circle(100.0); cout << "Radius: " << c->getradius() << endl; cout << "Area: " << c->getarea() << endl; When the object is no longer referenced by any variable, it will be freed from memory the next time the the CLR s garbage collection process runs. When creating managed classes, it is important that you understand the difference between reference types and value types. In standard C++, a class can be used as a value type, which means that you can create an instance of the class with a simple declaration statement. A managed class, however, is a reference type, which means that you must use the new operator to dynamically allocate an instance of the class. For example, had the Circle class not been a managed class, we could use the following code to create and use an instance of it. // This code works only with an unmanaged Circle class. Circle c(100.0); cout << "Radius: " << c.getradius() << endl; cout << "Area: " << c.getarea() << endl; This code will not work, however, with a managed Circle class because it is a reference type.

Appendix G: Writing Managed C++ Code for the.net Framework 7 Program G-1 An Example Program Now that you have an idea of what.net is, and have been introduced to the concept of managed code, let s look at an example of a managed C++ program. Program G-1 shows a simple "Hello world" program. This code is automatically generated by the Visual Studio.NET application wizard when you create a console application. 1 // This is the main project file for VC++ application project 2 // generated using an Application Wizard. 3 4 #include "stdafx.h" 5 6 #using <mscorlib.dll> 7 8 using namespace System; 9 10 int _tmain() 11 { 12 // TODO: Please replace the sample code below with your own. 13 Console::WriteLine(S"Hello World"); 14 return 0; 15 } Program Output Hello World Let s take a closer look at this program. First notice that the following directives appear after the comments. #include "stdafx.h" #using <mscorlib.dll> These stdafx.h header file is necessary because it includes all of the other system header files needed for a.net application. The #using directive is used to import an MSIL file into a C++ project. The directive shown here imports the mscorlib.dll file, which contains parts of the.net Framework that you will use the most. For example, all of the CTS data types are defined there. Next we have the following statement: using namespace System; This statement tells the compiler that we will be using the System namespace. The.NET class library is organized into numerous namespaces, and System is one of the most commonly used ones. In this namespace are the fundamental components of a.net application. For example, the names of the CTS data types are part of the System namespace. In addition, there are numerous other namespaces within the System namespace. For example, the System.Collections namespace contains classes that can be used to implement containers, and the System.Data namespace contains the classes needed to work with databases.

8 Appendix G: Writing Managed C++ Code for the.net Framework Program G-2 Next we have the following function header: int _tmain() Instead of main(), the application wizard creates a _tmain() function. If you prefer, you can use main instead of _tmain. Although we won t go into a detailed explanation here, the reason the application wizard automatically uses _tmain is because it provides some additional support for Unicode characters. Inside the _tmain function we see the following statement: Console::WriteLine(S"Hello World"); This shows a class from the.net Framework class library being used. This statement calls the WriteLine method, which is a member of the Console class. The Console class is in the System namespace. If we hadn t specified that we were using the System namespace, we would have to write this statement as: System::Console::WriteLine(S"Hello World"); Like cout, the Console::WriteLine method displays console output. Program G-2 shows another example. This program uses the code previously discussed to dynamically allocate a managed array of integers. The contents of the array are then displayed using the Console::WriteLine method within a loop. 1 // This program uses managed C++ code. 2 #include "stdafx.h" 3 #using <mscorlib.dll> 4 using namespace System; 5 6 int _tmain() 7 { 8 // Create an array of integers. 9 const int SIZE = 12; 10 int numbers gc[] = new int gc[size]; 11 12 // Store some values in the array. 13 for (int i = 0; i < SIZE; i++) 14 numbers[i] = i; 15 16 // Display the values in the array. 17 for (int i = 0; i < SIZE; i++) 18 Console::WriteLine(numbers[i]); 19 20 return 0; 21 }

Appendix G: Writing Managed C++ Code for the.net Framework 9 Program Output 0 1 2 3 4 5 6 7 8 9 10 11 Learning More An easy way that you can learn more about.net programming and managed C++ is through the Visual Studio.NET online help. Just click Help on the main menu bar, and then click Contents. You ll find an abundance of information there.