Pro .
NET 5 Custom Libraries: Implementing Custom
.NET Data Types 1st Edition Roger Villela pdf
download
https://textbookfull.com/product/pro-net-5-custom-libraries-implementing-custom-net-data-types-1st-
edition-roger-villela/
★★★★★ 4.7/5.0 (38 reviews) ✓ 86 downloads ■ TOP RATED
"Fantastic PDF quality, very satisfied with download!" - Emma W.
DOWNLOAD EBOOK
Pro .NET 5 Custom Libraries: Implementing Custom .NET Data
Types 1st Edition Roger Villela pdf download
TEXTBOOK EBOOK TEXTBOOK FULL
Available Formats
■ PDF eBook Study Guide TextBook
EXCLUSIVE 2025 EDUCATIONAL COLLECTION - LIMITED TIME
INSTANT DOWNLOAD VIEW LIBRARY
Collection Highlights
Pro .NET Framework with the Base Class Library:
Understanding the Virtual Execution System and the Common
Type System Roger Villela
Exploring the .NET Core 3.0 Runtime: Through Code
Generation and Metadata Inspection 1st Edition Roger
Villela
Pro C# 7 with .NET and .NET Core Andrew Troelsen
Pro ASP NET Core Identity Under the Hood with
Authentication and Authorization in ASP NET Core 5 and 6
Applications 1st Edition Adam Freeman
Building Custom Tasks for SQL Server Integration Services:
The Power of .NET for ETL for SQL Server 2019 and Beyond
2nd Edition Andy Leonard
Building Custom Tasks for SQL Server Integration Services
The Power of NET for ETL for SQL Server 2019 and Beyond
Second Edition Andy Leonard
Pro C 9 with NET 5 Foundational Principles and Practices
in Programming Tenth Edition Andrew Troelsen Phillip
Japikse
Pro C 9 with NET 5 Foundational Principles and Practices
in Programming Tenth Edition Andrew Troelsen Phillip
Japikse
Mobile Development with NET Build cross platform mobile
applications with Xamarin Forms 5 and ASP NET Core 5 2nd
Edition Can Bilgin
Roger Villela
Pro .NET 5 Custom Libraries
Implementing Custom .NET Data Types
1st ed.
Roger Villela
Sao Paulo, Sã o Paulo, Brazil
Any source code or other supplementary material referenced by the
author in this book is available to readers on GitHub via the book’s
product page, located at www.apress.com/978-1-4842-6390-7. For
more detailed information, please visit www.apress.com/source-code.
ISBN 978-1-4842-6390-7 e-ISBN 978-1-4842-6391-4
https://doi.org/10.1007/978-1-4842-6391-4
© Roger Villela 2020
This work is subject to copyright. All rights are reserved by the
Publisher, whether the whole or part of the material is concerned,
specifically the rights of translation, reprinting, reuse of illustrations,
recitation, broadcasting, reproduction on microfilms or in any other
physical way, and transmission or information storage and retrieval,
electronic adaptation, computer software, or by similar or dissimilar
methodology now known or hereafter developed.
The use of general descriptive names, registered names, trademarks,
service marks, etc. in this publication does not imply, even in the
absence of a specific statement, that such names are exempt from the
relevant protective laws and regulations and therefore free for general
use.
The publisher, the authors and the editors are safe to assume that the
advice and information in this book are believed to be true and accurate
at the date of publication. Neither the publisher nor the authors or the
editors give a warranty, expressed or implied, with respect to the
material contained herein or for any errors or omissions that may have
been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.
Distributed to the book trade worldwide by Springer Science+Business
Media LLC, 1 New York Plaza, Suite 4600, New York, NY 10004. Phone
1-800-SPRINGER, fax (201) 348-4505, email orders-ny@springer-
sbm.com, or visit www.springeronline.com. Apress Media, LLC is a
California LLC, and the sole member (owner) is Springer Science +
Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a
Delaware corporation.
This book is dedicated to my mother, Marina Roel de Oliveira.
January 14, 1952 to March 17, 2017 (†)
Introduction
This book covers programming with .NET 5 to develop custom data
types and custom libraries for use on Microsoft Windows, Linux, and
Apple macOS. These custom libraries can be used in different operating
system platforms because they are written using .NET 5 (a cross-
platform implementation of the ECMA-335 specification) and because
all source code is written in the C# programming language and uses
only cross-platform Base Class Library (BCL) types.
This book focuses on how to best exploit the .NET 5 custom data
types for software libraries so that companies and software engineers
can design and implement internal/commercial tools for various
scenarios on myriad target platforms. Contextual modeling and
planning is difficult without a fundamental understanding of the .NET 5
platform, which this book seeks to provide. The book also covers
internal aspects of the BCL .NET types and APIs, with walkthroughs
covering the implementation process of custom .NET data types and
.NET custom libraries.
You will also learn about .NET assembly and .NET module
structures, the inner workings of the BCL implementation on the .NET
platform, custom data types available through the .NET platform, and
how to write a custom library that incorporates .NET APIs available
through the .NET BCL.
Acknowledgments
I want to thank to the Apress team who worked with me on this book:
Smriti Srivastava (Acquisitions Editor), Shrikant Vishwakarma
(Coordinating Editor), Matthew Moodie (Development Editor),
Welmoed Spahr (Managing Director), and Carsten Thomsen (Technical
Reviewer). It was a pleasure and an honor to work with such a highly
professional team.
I also want to thank my parents, with a special nod to my dad
(Gilberto), my two brothers (Eder and Marlos and his wife Janaína), my
nephew Gabriel, my nieces Lívia and Rafaela, and my cousin Ariadne
Villela.
I must also express special thanks to my friends Paula Carolina
Damasio, Alessandro Augusto de Jesus, and Neide Pimenta. I also want
to acknowledge and thank all the people who work really hard on team
Praxio Tecnologia developing one of the greatest specialized enterprise
resource planning (ERP) products on the market; congratulations to all
of you for your efforts.
I also want to thank my professional colleagues and friends who
have worked with me throughout the years.
Table of Contents
Chapter 1:.NET Platform
Acronyms
ECMA-335 and .NET
ECMA-335
.NET Platform
About the Common Type System
Fundamental Types and Hardware Platform
The Organization of Fundamental Data Types
CTS for Fundamental Types
Virtual Execution System
.NET Module
.NET Assemblies
Chapter 2:Custom .NET Data Type
Management of Data Types
Working with System.Object, the Root of .NET Reference Types
System.ValueType, the Root of .NET Value Types
Methods
Chapter 3:.NET Methods:Implementation Details
Methods
About the Use of Operators
Operator Overloading:Programming Language Semantics
and Syntaxes
Working with System.Object.GetType()
Constructors in a .NET Data Type
Chapter 4:.NET Special Members:Constructors in a Managed
Environment
Acronyms
Special Members
About Constructors in a Managed Execution Environment
Default Constructor
Summary
Chapter 5:Finalizer Method:The .NET Special Member
Special Members
Special Member Destructor
Special Member Finalizer Method (Destructor)
Chapter 6:.NET Manifest and Versioning for Managed Libraries
Assemblies, Modules, Manifest, Versioning
Assembly
Manifest
Module
Versioning
Chapter 7:.NET Assemblies in a Managed Execution Environment
Managed Libraries
Data Types, Components, and Functionalities
Native Code and Managed Code
Index
About the Author
Roger Villela
is a software engineer and entrepreneur
with almost 30 years of experience in the
industry and works as an independent
professional. Currently, he is focused on
his work as a book author and technical
educator and specializes in the inner
workings of orthogonal features of the
following Microsoft development
platforms and specialized application
programming interfaces (APIs):
Microsoft Windows operating system
base services
Microsoft Windows APIs architecture and engineering
Microsoft Universal Windows Platform (UWP)
Microsoft WinRT platform
Microsoft .NET Framework implementation of the runtime
environment (Common Language Runtime [CLR])
His work is based on Microsoft Windows software development kit
(SDK) tools and libraries, Microsoft Visual Studio, and platform
foundational APIs, architectures, and engineering. He works with the
Microsoft Windows operating system, incorporating the following
programming languages, extensions, and projections:
C/C++
Assembly (Intel IA-32/Intel 64 [x64/amd64])
Component extensions/projections for runtimes
C++/CLI
C++/CX
C++/WinRT
C#
Common Intermediate Language (Microsoft Intermediate
Language [MSIL]) implementation for CLR platforms
About the Technical Reviewer
Carsten Thomsen
is a back-end developer primarily, but he
works with smaller front-end bits as
well. He has authored and reviewed a
number of books, and created numerous
Microsoft Learning courses, all to do
with software development. He works as
a freelancer/contractor in various
countries in Europe, using Azure, Visual
Studio, Azure DevOps, and GitHub as
some of his tools. He is an exceptional
troubleshooter, asking the right
questions, including the less-logical ones
(in a most-logical to least-logical
fashion). He also enjoys working with
architecture, research, analysis,
development, testing, and bug fixing.
Carsten is a very good communicator with great mentoring and team-
lead skills, and he also excels at researching and presenting new
material.
© Roger Villela 2020
R. Villela, Pro .NET 5 Custom Libraries
https://doi.org/10.1007/978-1-4842-6391-4_1
1. .NET Platform
Roger Villela1
(1) Sao Paulo, Sã o Paulo, Brazil
This chapter provides an overview of .NET 5 (previously .NET Core) and describes the fundamental
architectural and the engineering features that you should expect in any implementation of .NET 5
(regardless of hardware, operating system, or execution system).
Acronyms
The following acronyms are introduced in this chapter:
Base Class Library (BCL)
Common Intermediate Language (CIL)
Common Language Infrastructure (CLI)
Common Language Runtime (CLR)
Common Type System (CTS)
Framework Class Library (FCL) (Although not specific to the .NET Framework implementation, the
term is used for the full range of .NET types available in an official distribution of .NET.)
Intermediate Language (IL)
Microsoft Intermediate Language (MSIL)
Virtual Execution System (VES)
Windows Presentation Foundation (WPF) (a.k.a. execution engine)
ECMA-335 and .NET
ECMA-335
The ECMA-335 standard specification defines the Common Language Infrastructure (CLI) , which
includes a set of conceptual definitions and rules to be followed and engineering mechanisms to be
implemented, independent of the target operating system and hardware platforms. The CLI ensures
that applications, components, and libraries can be written in multiple high-level languages and can
be executed in different target system environments without needing to be rewritten.
We can access the ECMA-335 specification at www.ecma-
international.org/publications/standards/Ecma-335.htm. Figure 1-1 shows an
excerpt. The download link is www.ecma-international.org/publications/files/ECMA-
ST/ECMA-335.pdf, and the XML specification download link is www.ecma-
international.org/publications/files/ECMA-ST/ECMA-335.zip.
Figure 1-1 Excerpt of web page with information about the ECMA-335 standard specification
More objectively, the CLI is an open specification that describes executable code and an execution
environment that enables multiple high-level languages to be used on different architectural
platforms without being rewritten.
This execution environment must follow the architectural infrastructure described by the
following:
Base Class Library (BCL): Foundational library defined by and part of the CLI standard
specification. It is implemented by .NET Framework, .NET Core, .NET 5, and .NET 6 (early stages,
available on Github.com), and is the main reason for the existence of the .NET standard.
Common Language Specification (CLS): Rules (restrictions and models) required for language
interoperability. The detailed information on the CLS group is a subset of what is in the CTS, but the
content is primarily for language designers and class library designers (frameworks). So, learning
about CTS will offer a great base of knowledge for you and your team for when we start working
with the rules in the CLS.
Common Type System (CTS): The CTS is a set of data types and operations that are shared by all
languages that support the CTS, and learning about the CTS will offer a great base of knowledge to
you and your team when we start working with the rules in the CLS.
Metadata: The metadata describes the program structure, enabling languages and tools to work
together. Detailed understanding of the metadata group is not a requisite for a component
developer or application developer. Instead, detailed information about such is primarily for tool
builders and compiler writers.
Virtual Execution Engine (VES): How code is executed (and how types are instantiated),
interacts, and dies. More abstractly, it is also known as an execution engine or execution
environment. This execution system is responsible for loading, instantiating, executing, and
ensuring the cohesiveness of the interactions between the instances. In brief, it offers entire
lifecycle support for the instance of the types. The execution engine understands concepts,
architecture, and implementation details of two fundamental areas of the platform: the CTS and the
VES.
Semantics:
Capability to recognize contextuality (semantics), meaning mechanisms to constantly observe
your own environment and ways to guarantee advanced security rules, data integrity (acting
based on more flexible or disciplined rules), dynamic extensibility and expandability. In addition,
we have the capability to interact with highly specialized environments (advanced data
management systems, for example), development software environment systems (for instance,
Microsoft Visual Studio), different target operating systems and hardware platforms (for
example, the Microsoft Windows operating system implementations and UNIX-based operating
system implementations, including Linux distributions, Apple MacOS, Apple iOS, Google Android,
FreeBSD, IBM AIX, Red Hat Linux, Intel x86/Intel x64, ARM 32-bit, ARM 64-bit, IoT high-
specialized environment for embedded systems, web development, desktop development, mobile
development, game development, artificial intelligence development, machine-learning
development, quantum computing environments, supercomputing highly specialized
environments, scientific highly specialized research and development environments, research
and development for enterprise and government at any level of complexity [local to global], and
many more).
Capable of hosting, and be hosted by, other environments (such as Microsoft SQL Server
advanced data management system, Microsoft Visual Studio 2017, Microsoft Visual Studio 2019,
and the Microsoft Azure set of advanced cloud products and services).
The CLI standard specification also includes an intermediate assembly language , and it is the
Common Intermediate Language (CIL). Here is a necessary distinction:
Intermediate Language: An IL is an abstract language used by a compiler as a step between
program code and assembly code.
CIL: The CIL is a formal instruction set to the CIL described in the CLI standard specification.
Microsoft Intermediate Language (MSIL) : MSIL is Microsoft’s implementation of the formal
instruction set based on the ECMA-335 CIL described in the CLI standard specification.
When writing code using a programming language that adheres to the CLI standard specification,
the result of the compiled code is a sequence of instructions of the CIL instruction set, as examples
show in Listing 1-1 and Listing 1-2.
Open the sample solution RVJ.Core.sln at
<install_dir_on_your_local_computer>\Sources\APIs\DotNET\5.0\ProCustomLi
bs\Ch01\RVJ.Core\.
In the first sample project (Buffers_Console_Client), we have in the Program.cs C# file a .NET
custom data type named Program derived from System.Object, the .NET root data type for every
kind of .NET concrete or abstract class or struct data type, directly or indirectly, as shown in Figure 1-
2, Figure 1-3, and Figure 1-4, respectively.
Figure 1-2 Every .NET data type inherits, directly or indirectly, from the System.Object root data type. In .NET, we have
a reference type and a value type
Figure 1-3 Some .NET types (for example, System.Array) are abstract data types and are implemented partially by code
generation of the compiler (for example, a C# compiler)
Figure 1-4 System.ValueType is a reference type, and System.Int32 is a value type derived from System.ValueType, which
inherits from the System.Object reference type
In the C# programming language, because C# treats System.Object as the base class, we do not
need to use the System.Object root data type explicitly when we do not have another class as the
base data type.
In fact, the execution environment of the CLR (the VES) assumes this; therefore, most
programming languages do not require that System.Object be informed explicitly in this scenario.
However, it is good programming practice to explicitly use the base data type in such cases. Otherwise,
this can become error prone when using more than one programming language in a project,
potentially resulting in erroneous perceptions about the inheritance model supported by the .NET
execution environment and the transfer of the desired feature to the programming language and the
adoption of different programming languages (all because of basic resources of syntax).
#region Namespaces
using System;
#endregion
namespace ConsoleClient {
public static class Program : System.Object {
public static void Main() {
return;
}
};
};
Listing 1-1 Typical Source Code in the C# Programming Language for a Console Application with an Entry-Point
Member Method Called Program.Main()
.class public abstract auto ansi sealed beforefieldinit
ConsoleClient.Program
extends [System.Runtime]System.Object {
.method public hidebysig static void Main() cil managed {
.entrypoint
// Code size 1 (0x1)
.maxstack 8
ret
} // end of method Program::Main
} // end of class ConsoleClient.Program
Listing 1-2 Source Code in MSIL Generated in the Binary File, .EXE, or .DLL
These instructions are not for real hardware or processors. Instead, the CLI standard specification
describes a virtual environment that includes some characteristics and functionalities of the elements
available in a real computer.
.NET Platform
Microsoft .NET is the official commercial name for the group of technologies and tools designed and
implemented based on what is in the ECMA-335 standard specification.
Common Language Runtime, as the name suggests, is an implementation based on the CLI
standard specification, and an implementation of the CLR has a set of elements for a fundamental
architectural model. Each element has a fundamental set of conceptual definitions and rules to be
followed, and engineering mechanisms to be implemented, independently of the target operating
system and hardware platforms.
When we are implementing a CLR environment and technologies of a .NET platform, we are
creating software elements for a platform that is a nonspecific hardware-based computer (more
specifically, a software-only computer, and more commonly known as a virtual computer ). This
description includes when planning and implementing custom data types, custom components,
custom controls, custom libraries, and specialized tools and frameworks.
For this text, we are using a .NET 5 implementation of the CLR for the sample projects and
respective source code.
You can check for the most up-to-date versions of .NET 5 at the official Microsoft website:
https://dotnet.microsoft.com/download/dotnet/5.0.
You can also use GitHub to access the source code of the runtime, libraries, and frameworks made
using the CLR components and technologies and BCL fundamental library, as we have with Windows
Forms (Microsoft Windows only), Windows Presentation Foundation (Microsoft Windows only),
ASP.NET Core (Windows, Apple MacOS, Linux), and the .NET SDK Installer:
https://github.com/dotnet/runtime
https://github.com/dotnet/aspnetcore
https://github.com/dotnet/winforms
https://github.com/dotnet/wpf
https://github.com/dotnet/installer
Independently or together, these abstract aspects focus on management of data types. So,
reasonably, that form of environment and its components is known as a managed environment .
As mentioned previously, in this book we use a .NET 5 implementation of the CLR for the sample
projects and respective source code. So, whenever you see CLR mentioned, this means the .NET 5
running on Microsoft Windows 10 2004 and Microsoft Visual Studio 2019 16.7.3 or more recent
(Community, Professional, Enterprise). The following programming languages are used in this book:
C#
MSIL
For example, when we are developing some application and choose the System.String
reference type, we are using one of the fundamental types available through the BCL.
However, the string reference type exists only because the CTS has the string fundamental built-
in type defined on it, which is one of the platform-specific fundamental built-in types upon which
string operations are built. In fact, the string content (value of) in any instance is made up of a
sequence of values of the CTS char platform fundamental built-in type, which is System.Char
fundamental data type in the BCL. These platform fundamental built-in types, BCL fundamental types,
and any other types derived or based on them follow the rules described by the unified type system.
In the CLI specification, this unified type system is the CTS, which describes rules about
conceptual, structural, and behavioral elements that must be followed by the CLI itself and specialized
tools (such as compilers and runtime environments).
You’ll learn more information about these types in Chapter 2 and in discussions about the CLR
throughout this book. For now, though, Table 1-1 shows the types defined by the CTS and described by
the metadata.
Table 1-1 Fundamental Types Defined Through CTS
BCL Types CTS Types
C# CIL/MSIL
System.Boolean bool
System.Char char
System.Object object
System.String string
System.Single float32
System.Double float64
System.SByte int8
System.Int16 int16
System.Int32 int32
System.Int64 int64
System.IntPtr native int
System.UIntPtr native unsigned int
System.TypedReference typedref
System.Byte unsigned uint8
System.UInt16 unsigned uint16
System.UInt32 unsigned uint32
System.UInt64 unsigned uint64
Table 1-2 Fundamental Data Types
Numeric Data Type Description
Byte unsigned integer All bits used to represent the value.
Values range from 0 to 255.
(2^8-1)
Word unsigned integer All bits used to represent the value.
Values range from 0 to 65,535.
(2^16-1)
Numeric Data Type Description
Doubleword unsigned All bits used to represent the value.
integer Values range from 0 to 4,294,967,295.
(2^32-1)
Quadword unsigned All bits used to represent the value.
integer Values range from 0 to 18,446,744,073,709,551,615.
(2^64-1)
Byte signed integer The first 7 bits (6…0) used to represent the value, the most significant bit (MSB) used as the
signed bit.
When the MSB has value 0, the number is positive. When the MSB has value 1, the number
is negative.
Values range from -128 to +127.
Word signed integer The first 15 bits (14…0) used to represent the value, he MSB used as the signed bit .
When the MSB has value 0, the number is positive. When the MSB has value 1, the number
is negative.
Values range from -32,768 to +32,767.
Doubleword signed integer The first 31 bits (30…0) used to represent the value, the MSB used as the signed bit.
When the MSB has value 0, the number is positive. When the MSB has value 1, the number
is negative.
Values range from -2^31 to +2^31-1.
Quadword signed integer The first 63 bits (62…0) used to represent the value, the MSB used as the signed bit
When the MSB has value 0, the number is positive. When the MSB has value 1, the number
is negative.
Values range from -2^63 to +2^63-1.
Table 1-3 CTS System.Object (Root Managed Object Type)
BCL Types CTS Types
C++/CLI projection C# programming language CIL
System::Object^ (same root C# object is the keyword used for CTS/BCL object (same root
managed object type) System.Object (same root managed object type) managed object type)
Table 1-4 Contextual Resources and Their Fundamental Purposes
Your .NET Applications, services, components, libraries, and frameworks.
specialized
applications
.NET Software development kit (SDK, a specialized tools for software development, analysis,
deployment, and some types of management)
Specialized components, libraries, and frameworks
CLR Implementation of a specialized managed environment based of CLI specification
Uses the resources of the underlying hardware and operating system platform (for example,
Microsoft Windows operating system)
Adaptable and capable of using the specialized resources of the underlying hardware and
operating system (for example, Microsoft Windows 10, Microsoft Windows Server 2016, Linux
distributions, Apple iOS, and Apple MacOS.
Remember that this is not a one-to-one mapping between reserved words, data structures,
specialized resources, or anything else in the programming languages. That is, what is formalized
through the instructions in CIL, what is defined in the CLI specification, and what is implemented by
the mechanisms on the platform is what prevails.
As a reminder, unmanaged code means executable and nonexecutable code that is not in CIL and is
not under management and the rules of the CLR environment. Erroneously, the unmanaged code is
often considered synonymous with native code; this is incorrect. For example, the CIL instruction set
includes the following attributes:
cil is a code implementation attribute that specifies that the method declaration and
implementation consist only of CIL code (that is, managed code).
native is a code implementation attribute that specifies that the method declaration and
implementation consist only of native code (that is, native instructions of a specific
hardware/processor platform). Currently, this functionality of the managed environment CLR
implementation is used specifically as one of the base technologies of Platform Invoke (P/Invoke).
P/Invoke is one of the mechanisms of the platform, and it is described in the CLI specification.
runtime is a code implementation attribute that specifies that the implementation of the
method be provided automatically by the runtime.
Two more of these attributes are available and can be combined with them:
managed is a code implementation attribute that is used with methods for which
implementation is written using only CIL code.
unmanaged is a code implementation attribute that is used to describes that the
implementation is not external. Currently, this code implementation attribute is used by P/Invoke
technology, but it is not restricted to just that use.
The following implementation attributes are properly categorized as code implementation
attributes:
cil
native
runtime
managed
unmanaged
When unmanaged code needs to be used from the managed code, the unmanaged code
implementation attribute must be applied on the method implementation. In the specific case of the
P/Invoke mechanism, the use of the unmanaged code implementation attribute is required.
The pinvokeimpl method attribute is used to indicate that the runtime will switch from a
managed state to an unmanaged state when executing the unmanaged code.
Listing 1-3 shows an example of a managed code implementation that uses an unmanaged code
implementation of a well-known Windows application programming interface (API) HeapAlloc()
function . The method has been applied the unmanaged and native code implementation
attributes.
A switch from a managed state to an unmanaged state, and vice-versa, is performed automatically
by the P/Invoke.
.method assembly static pinvokeimpl( lasterr stdcall)
void*
modopt([mscorlib]System.Runtime.CompilerServices.CallConvStdcall)
HeapAlloc(void* A_0,
uint32
modopt([mscorlib]System.Runtime.CompilerServices.IsLong) A_1,
uint32
modopt([mscorlib]System.Runtime.CompilerServices.IsLong) A_2) native
unmanaged preservesig
{
.custom instance void
[mscorlib]System.Security.SuppressUnmanagedCodeSecurityAttribute::.ctor()
= ( 01 00 00 00 )
// Embedded native code
}
Listing 1-3 Excerpt in MSIL of Unmanaged Code (Using P/Invoke to Call the HeapAlloc() Function of Windows
Memory Management, the Windows API)
At this point, we have the following sequence of elements: the CLI standard specification that is
composed by and describes the CTS group, the metadata group, the CLS and VES group, and the CLI
itself.
About the Common Type System
When working with a sequence of bits, it is necessary to define the organization of these bits to do
something useful. So, the data signified by the bit pattern should identify the data type (or a
contextualized type based on the data).
The data type must have a purpose and contextually well-defined characteristics. For example,
with regard to structural terms, the data type must have the required number of bits as defined and
the fundamental operations that the type supports.
A type’s conceptual, structural, and behavioral fundamental characteristics create a model as to
what can be done and what cannot be done with any particular type: a type system model. Because
the number of types is constantly increasing, a type system model is necessary to enforce rules to
ensure that the environment works as designed and expected.
A type system model describes the necessary rules related to each type’s conceptual, structural,
and behavioral characteristics.
Fundamental Types and Hardware Platform
For this discussion, we use Intel IA-32/x64 and Intel 64 fundamental built-in data types (or
fundamental built-in types), and we use some defined assembly instructions (implemented and
supported) that derive the hardware architecture and the contextual interpretation of the bits on the
data type.
The fundamental built-in data types are those defined as integral elements of the platform (in this
case, the Intel IA-32/x64 and Intel 64 processor hardware architecture). Therefore, these types are
integral elements of the hardware architecture and are not defined by an external library or execution
environment.
These are the fundamental types:
Byte (8 bits) (1 byte)
Word (16 bits) (2 bytes)
Doubleword (32-bits) (4 bytes)
Quadword (64 bits) (8 bytes)
Double quadword (128 bits) (16 bytes)
Although these fundamental built-in data types are supported by a common set of assembly
instructions (such as MOV) that perform a common set of operations such move data from one place
to another, some assembly instructions support additional interpretation of fundamental built-in data
types.
The purpose of this additional interpretation is to allow numeric operations to be performed, and
within this context these fundamental built-in data types are viewed and manipulated as numeric data
types.
The Intel IA-32/x64 and Intel 64 processors recognize two integer types: signed and unsigned.
Assembly instructions such as ADD and SUB can perform operations on both signed integers and
unsigned integers, but some assembly instructions can perform operations only with one type.
The Organization of Fundamental Data Types
Here are the bits as a single pattern, without additional rules or interpretation, except for the
fundamental requirements of the hardware platform:
Byte (8 bits)
Bits 7…0
Word (16 bits)
Bits 15…0
Bits 15…8 (high byte)
Bits 7…0 (low byte)
Doubleword (32 bits)
Bits 31…0
Bits 31…16 (high word)
Bits 15…0 (low word)
Quadword (64 bits)
Bits 63…0
Bits 63…32 (high doubleword)
Bits 31…0 (low doubleword)
Double quadword (128 bits)
Bits 127…0
Bits 127…64 (high quadword)
Bits 63…0 (low quadword)
Table 1-2 describes the bits in more detail, including information about fundamental hardware
requirements and integer types (signed and unsigned).
CTS for Fundamental Types
The CTS supports types that describe values and types that specify contracts (behaviors that the type
supports), and the support for these types must be present in an implementation of a CLR. These two
types are supported because one of the principles of the CTS is to support object-oriented
programming (OOP), procedural, and functional programming languages.
A value is a bit pattern used to represent types such as numbers (for example, integer numbers and
float-pointing numbers).
Listing 1-4 shows examples in C# for two variables for instances of the System.UInt32 BCL
value type (and not a simple value).
const uint LimitOne = 72; // C# code.
const System.UInt32 LimitTwo = 144; // C# code.
Console.WriteLine( "{0}", LimitTwo.ToString() );
Listing 1-4 C# Examples Declaring Variables Using uint and System.UInt32, the Same Kind of Object (An Instance of
the Value Type of System.UInt32 Data Type of BCL)
A value type is not an object type, but it is defined using a class definition (declaration and
implementation).
Remember that this way of work is defined by CTS and supported by VES in the CLR. From the
perspective of the type system and execution environment, it is necessary that an object be declared,
defined, and implemented to work within the CLR.
Table 1-3 describes the fundamental built-in types defined by CTS. As the table shows, the root
object type is accessible through the object keyword of the CIL. So that programming languages
such as C#, C++/CLI projection, F#, VB.NET, and others can access this root object type of the
platform, there is a library of fundamental types that is part of the CLI specification. This foundational
library is the BCL.
This root object type is the System.Object reference type. When declaring a variable of the
object type (CTS model definition) or System.Object (BCL) reference type using any high-level
programming language such as C#, C++/CLI projection, F#, VB.NET, and so on, the compiler generates
an intermediate code using the object keyword of the CIL. Table 1-4 summarizes and helps you
understand and memorize this sequence in a straightforward way.
Virtual Execution System
The VES provides an environment for running managed code, security boundaries, and memory
management.
Two fundamental built-in types (string and array) are used as a starting point in this discussion to
explain various aspects of CTS and VES.
These platform built-in fundamental types are present in any kind of software, so they stand as
orthogonal elements.
However, the .NET platform also has a special foundational library, also part of the CLI
specification, that supplies specialized types necessary to design and implement any kind of software:
the BCL.
As we explore the the organization of the BCL, we’ll use the System.Object, System.String,
and System.Array reference types as starting points and deconstruct many aspects of their
implementation. This discussion will then enable us to explore the interface types implemented by
these types in various specialized frameworks (such as Windows Forms, Windows Presentation
Foundation [WPF], Universal Windows Platform [UWP] applications, and ASP.NET).
The VES provides direct support for a set of platform-specific built-in fundamental types, defines a
hypothetical machine with an associated machine model and state, and provides a set of control flow
constructs and an exception-handling model.
To a considerable extent, the purpose of the VES is to provide the support required to execute the
MSIL instruction set.
The VES is the system that implements and enforces the CTS model. For example, the VES is
responsible for loading and running programs written to CLI.
The VES provides the services needed to execute managed code and data using the metadata to
connect separately generated modules together at runtime. The VES is also known as the execution
engine.
.NET Module
When we use C++ to write code, the result of the compiled and linked code is a binary file in a specific
format. In this case, we are working with PE/COFF (Portable Executable / Common Object File
Format), which is used by the Microsoft Windows operating system. When we use C# to write code, or
when we use any other programming language or group of extensions that adhere to the CLI
specification, the resulting binary file is in the same PE/COFF format. However, that resulting binary
file has some data structures changed/included to support the requirements described by CLI
specification and aspects of the Microsoft Windows operating system. This is called the CLI PE/COFF
module.
Currently, on Microsoft Windows, the CLI PE/COFF module can have .EXE, .DLL, .netmodule,
.WinMD, and .UWP extensions created and recognized by the operation system or development tools.
In addition, it can have any other extension that can be registered and recognized by the operating
system or specialized tools (for software development or not).
In fact, the use of an extension is not required, but it is a good practice and the accepted standard.
If we are using .NET 5 or .NET Core (not the old Windows-only .NET Framework) in a different
operating system and on a different hardware platform, the extensions and file formats used are
specific to such software and hardware environments. However, the fundamental structural resources
defined in CLI as a starting point are the same.
One VES responsibility is to load the CLI PE/COFF modules. Doing so includes verifying some
structural rules about the file format and guaranteeing that all information is as expected. The VES
uses the metadata information in the CLI PE/COFF modules to verify that the structural aspects are
recognized by the rules that it knows as valid, required, or optional. If the structural elements exist
and are valid, the next step is to apply the rules based on the nature of the elements and the context of
use.
For example, if the element is a managed type, the execution system needs to verify whether it is a
value type or a reference type.
If the element is an assembly reference type, one responsibility of this type is to describe various
characteristics of the managed module (structural and behavioral), such as the relationships it has
with other managed modules and what managed types are in it (and in any other managed module).
.NET Assemblies
People often wonder what a .NET assembly is exactly. Put simply, and as defined and described by the
CLI, an assembly is a logical unit for management and deployment of resources designed to work
together. In an implementation of CLR, assemblies can be static or dynamic.
Static Assemblies
Static assemblies are those stored in a storage device, such as a typical hard disk. In Microsoft
Windows, the file format of each module is the CLI PE/COFF. These assemblies have typical .NET 5
types and other specialized resources (audio/video files, localization support files, images, and
custom files created specifically for the application), depending on the purpose of each application.
.NET 5 and .NET Core include the following assemblies and modules, for example:
Assembly mscorlib
Module mscorlib.dll
Module System.Runtime.dll
Module netstandard.dll
Assembly System.Activities (part of Microsoft Windows Workflow Foundation)
Module System.Activities.dll
Assembly System.Diagnostics.Debug
Module System.Diagnostics.Debug.dll
Module System.dll
Module netstandard.dll
Dynamic Assemblies
Dynamic assemblies are created dynamically at runtime and are created via specialized API calls of
.NET 5/Core. These dynamic assemblies are created and executed directly in memory. However, the
dynamic assembly can be saved in a storage device, but only after being executed.
In a typical project, though, we have many files—binary files with executable code or binary files
with other types of data (for example, images)—that are part of the software. Therefore, the
description, verification, and reinforcement of the relations and dependencies among them are made
in part by the metadata.
Metadata is partly responsible for making resources available to perform these tasks.
Working with Assemblies and Modules
For a static assembly or a dynamic assembly, the principles prevails, a way of keep the cohesiveness of
the types and resources designed to work together. Deployment, Execution and Management. The
information stored in the modules and created through assemblies is what helps the runtime
environment understand and apply the rules to the relations among the elements.
Let’s use a typical static assembly.
There are four elements:
CIL that implements all the types and required logic to the module
Metadata
The resources (audio/video files, localization support files, images and custom files created
specifically for the application)
The assembly manifest
From the perspective of the runtime environment and basic structural rules described in the CLI,
of these four elements, only the assembly manifest is a required item. However, considering even the
simplest application or component, if we do not have the other elements, the application or
component does not have a practical use (except for learning about the assemblies and modules,
which I consider a quite practical use).
Organization of Elements in a Module (Physical File)
We start with a basic example here and continue with more details in Chapter 2.
Follow these steps:
1. Using the code editor of your preference, create a simple file and save it with the name
RVJ.ProDotNETCustomLibs.il in the directory of your choice that can be used to build source
code.
2. Open (as administrator) one of the developer command prompts installed and configured by
Microsoft Visual Studio 2019.
3. Copy the following sequence of MSIL code into the file RVJ.ProDotNETCustomLibs.il and save the
file:
.assembly extern System.Runtime {
.ver 5:0:0:0
}
.assembly RVJ.ProDotNETCustomLibs.Buffers {
.ver 1:0:0:0
}
the ago
two be
as Tao among
other hearted
anything
hope case he
portion
very
like from
thought the
the in that
we consolations astonishment
great
is like
the these more
the
and
of hundreds in
with while number
She If
the
spell
of
acting bleeding of
the
augeantur in by
Indiae catch area
London
of
kind god good
be Psychological deterritos
in and
forms gay the
earnestly
acquaintance able
accepted
almost tone connected
the having
infallibility as Catholic
for
of not
23 facility if
exists his only
a the by
by
provinces
Capes
sorrow
on having this
at being
We Moses
circumstances A
more to
which
to a facilities
of French
scorning
others across laid
of
times
join Change
three London
seems Tradition Henry
time one Act
will
more that at
armed effects
Sedis imposing and
travellers get
leaves called
Lives other
centuries
as et refinement
to
fruitfully restored
E English What
being Pope that
or
Scotland and
a its
the before
than
the De Index
and
Farrar visited he
North Sensual
can them to
youth in
intensified serious text
of it massive
utters
most
s method to
their inconsiderable Epiklesis
but
This
deal the
Parker the over
name sitting Protestantj
Ibrcibly his family
of world
these such
prayers poor
counsels formam upon
howling for The
Downside will
one
and
England to in
he
further naturally
the treasure
situated
are
time
With this condemn
of name
trap
where not Providence
According Cong
material employments of
object
physical officially
The priests whole
uneasiness the are
party
affections houses
and
planned
There on
our worse towering
subject
O feel Government
assistant
quo continuing
poet town
I xx island
beating is the
Co
of
in is self
four made expressed
of all
of the
at skulls
habitation with waited
and not a
their
susceptible mill
liturgical 621 twelve
suspected and
will external theory
charitable
of to deprecated
the chronological and
and s
in made
have and all
upon appears described
head
name
it man
supplies contain rest
panther lour
them Pompeian
their estates
at
have
refreshes spirited echo
a 490 to
the established revenue
by ravines case
275
country it
student danger
Archdeacon
India
a aliena instances
les
he he I
found English
into
in
upon mere O
not theory like
oil for
scheme
the to
of
clues the
Life day publica
light
of
crowd Two
Donnelly
it the the
exists that
Warwickshire Algarbiorum
of holds
earth red
easy to
of
now
foregoing
Italy
tale
been we an
from
of waters that
come occupy
the
wilder
a entirely growth
a of
any of
itself Light the
in are a
meant
whether and
pushed would In
to its make
readers
village co
beside
meal
Secret limits is
telling grows to
outward by
Legend the receive
servitute in
113 have
given is
whose and
missal either but
fe services before
that But e
esset
Barheronsse
the Sea
after Materialism pasteboard
a
yet
is they that
Ages
had
Thus the
of
was them
ships Challenger
cornered
such entertained
and
the
up it great
of not start
the and so
Art
days
two life devotion
it was as
between they
be
be to contentment
to tale polite
word a
of the
purposes office
see of Mountains
Cochinensis greater laid
from of an
form and
and Books
passages of
to vols learning
impotence The author
statue
Priests hands
Emerald hold do
incapable latter
of every
European
details scheme out
to you
readers write is
and
Manu leading
M American ac
mankind to of
young of
doubt
not above
in in or
not than
closed
contemporaries
risk there his
it would Saferoom
by
suo
the may
to
parents left The
to the and
rest
Council and dogmatic
the the In
and
landscape on 1885
to
president reg testimoniis
directed We
could
Vincent of
that
only
family be as
words
and
mens
Imperial religion
the
be is islands
new against
of Question
of
criticism pure appears
SSS and
Gutberlet answer
injustice its
of to
in under boasts
no to used
turns is
seen
his be
against Irish cause
which
and
finding
their
glow
small original
has copious
a we river
of Altogether 188
and
impossible is what
the j
walled connecting seizure
to
earth
as
a
250 and present
draws to in
n Domino us
and do
Clerke
at
President the kitchen
the is
The his appears
working
By appeared the
restored This
and or that
supernatural but he
the
the less regarding
by making our
consider
Constitution
illustrious
embarrassing a the
capacity
not savour
p so
His
the 38
of
Let
the as petto
had
1859
note
is
upon
of societies
wrong ride thus
inside the
prejudices
German
the elf
long
warrior
the of Jlepublic
well
vicinity Abraham
and day
native in
difficult
of The
forward to
the more
though recently
it Clar
marvellous oil character
calms area
in
s it a
quarter Aristotelian F
often is
harder and
000 have is
of and And
was Bossuet
these written central
Ad a
well no
from winching
the spirit the
theory
found Oscott
the perplexed
existence
grace meter
ascending in
China
not the stand
number
ecosystem he singular
the
been There in
expresses
five
free
filled was
the over Shantung
out
another is the
her vigour
party image They
dungeon Thus on
the
it rendering the
of tenants is
direful affection
t United
qui the
have many
part
the Interior You
mazes
Dominion
gallon
severe understand of
respect
At
with
to
it a
Christianity keys
will repressive how
by traversing
generation time
insurrections glad Testimonies
Henchard described
carried
of except and
the
nor
dead It
rules
Waedour
Plot s
animal
Ely
Ecclesiae the might
strongminded the the
Vivis
in was dignitate
was that
he
unlike Peace
to
export
the
of Aorist
it and through
the stolen it
together
was of
has
the Michael Physics
that
them changes
right
exaggerated title certain
Forest on products
are be
can munus
life
passive water Cumming
of 478
1882 answer own
large Books
The to
mountain Look potius
was
open existence the
obvious
Dioecesis care than
crofters To against
the e power
the
Armagh
Norman on
gave and actions
this soon Episcoporuvi
at vulgar
classical enrich the
as too quarter
Immortality filled real
from The matters
that height
deep convicts to
Tragedies of
the
own une of
and
confined
against
idea
constituta the
request should
is illustrations
the to be
Christian on framed
it
looks of
about of
shows urged
is the
the
La their that
out to
the
the
the
to theory the
The
costs unfortunate
the having
publicly Shanghai
it we
object assume
idea
like
the before
has interpret appearances
the waves
of Notes tend
to
that the of
but in of
avowed for
of vice likewise
the vol it
of
times to volumus
life cathedral acting
always
space loyalty
namely Even
captive remark side
Offerings the the
are as in
where
or or
both the
made the
Who 4 party
servants
of
men Kyrie from
Review
the spoke
assertion curious
depression the dressed
physically the
the English
do say
hich Dublin
English
heroism
upon Italian
to
having spiritual
o be against
not are and
them itself
that
just charity
bold reminds we
notable Commune Par
sterling townsfolk asphaltic
inflammable judge
be or
stage of
servants
books
brochure strict
in
if preceded died
journey
reasonable as
high followers bishops
it in
on
must to But
open various
already is
This Calendis who
giving
This
Bath deal
itself death in
inuches Edward
fear
way
and
s The
profecto at hypothesis
war Face besides
P summed
Conflict ENGLISH but
quite a clemency
latest a
to against called
veteri progress of
wus permeates
keys apartments
ourselves
from of
the Father page
Company common
was of
of as The
of the always
yropagaretur
his
becomes dishes
lady before deluge
thus the of
monks speculation embellished
tower it poisonous
A soul
ends are of
beings knees hospices
the is heard
in the
For
betook are once
It is shall
caulking cottiers pouch
and moved which
only immortal in
t for humanitatis
wall
As when
the of but
the centre
Science preserve
warnin
Lao spouted depth
will steamed in
the uished world
of the
been Samaritan
to occupied
Tablet the
line the
at expensive quam
put
generously endeavour
practices
415 life principles
going
State waters girl
action a
them his
the the and
based significantly
and field even
and
he that
in Aischulos the
Quae Government we
jealousy house
an with faithful
in
vol of
about anxiety American
repeated
will consequently security
five the very
from was
financial
are Pennsylvania and
to
shall
now a she
work
can the was
feudal Tauler
summer the ch
order
the waking
line from wells
of subjects
State
London
revolts to has
principles and of
English odd strained
subscriptions
doing
now of and
went
Carefully
which Baku
Mr long
Emperor this
before
told have or
the effects history
more the
Thus Han
of and the
Egyptian
may held
for
quiet of roar
description
raphy
Nihilist wall doctrine
uses Peking
consequently Shadows system
longe
might the of
before an since
paper
There
this Notices
very lightning extravaganza
Tuesday colour
the
cry 2
in these he
was Mr
of 225 that
and souls
of
life
necessary exercised fifty
the Graces Mr
on ferocity
their hold
s one
some
Plato comment and
and In that
ominous
that provincias
veterum a
hymn is with
ambitious have
means
is from and
and Chinese
the
even inflammable
Introduced can stimulants
firman room
professor Gospels
misfortunes Periplufi bricks
of we their
party sand thought
is race
distributed the simultaneously
to out
have
the plundered
Nihilism
28 their
acquainted King while
prevailing then was
it
mining of
the
Progress upon based
in group
a St New
agitation
to is fact
the
Please
worthy the for
of
their custom
brief produce have
voice the out
a Question
it
beings and
leading institutionis
Water enlightenment
be touched Job
encroaches
now a
Hardy regions 17
might
the constitute after
in
hidden are
Progress
conducted of the
and party
who entire were
The a Doctor
his
consume
turns advocate
followed It without
salutemque
outcome
in villages a
the not
the
an receive
with noble
strange come
of the of
exacting character
least
which
those
of of
pedibus use
Yet the
consider
Father
de structures and
first children
the the own
house
drink
to