old-www/LDP/LG/issue84/ortiz.html

358 lines
16 KiB
HTML

<!--startcut ==============================================-->
<!-- *** BEGIN HTML header *** -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<HTML><HEAD>
<title>Programming Bits: Meeting C# and Mono LG #84</title>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#0000FF" VLINK="#0000AF"
ALINK="#FF0000">
<!-- *** END HTML header *** -->
<!-- *** BEGIN navbar *** -->
<IMG ALT="" SRC="../gx/navbar/left.jpg" WIDTH="14" HEIGHT="45" BORDER="0" ALIGN="bottom"><A HREF="orr.html"><IMG ALT="[ Prev ]" SRC="../gx/navbar/prev.jpg" WIDTH="16" HEIGHT="45" BORDER="0" ALIGN="bottom"></A><A HREF="index.html"><IMG ALT="[ Table of Contents ]" SRC="../gx/navbar/toc.jpg" WIDTH="220" HEIGHT="45" BORDER="0" ALIGN="bottom" ></A><A HREF="../index.html"><IMG ALT="[ Front Page ]" SRC="../gx/navbar/frontpage.jpg" WIDTH="137" HEIGHT="45" BORDER="0" ALIGN="bottom"></A><A HREF="http://www.linuxgazette.com/cgi-bin/talkback/all.py?site=LG&article=http://www.linuxgazette.com/issue84/ortiz.html"><IMG ALT="[ Talkback ]" SRC="../gx/navbar/talkback.jpg" WIDTH="121" HEIGHT="45" BORDER="0" ALIGN="bottom" ></A><A HREF="../lg_faq.html"><IMG ALT="[ FAQ ]" SRC="./../gx/navbar/faq.jpg"WIDTH="62" HEIGHT="45" BORDER="0" ALIGN="bottom"></A><A HREF="qubism.html"><IMG ALT="[ Next ]" SRC="../gx/navbar/next.jpg" WIDTH="15" HEIGHT="45" BORDER="0" ALIGN="bottom" ></A><IMG ALT="" SRC="../gx/navbar/right.jpg" WIDTH="15" HEIGHT="45" ALIGN="bottom">
<!-- *** END navbar *** -->
<!--endcut ============================================================-->
<TABLE BORDER><TR><TD WIDTH="200">
<A HREF="http://www.linuxgazette.com/">
<IMG ALT="LINUX GAZETTE" SRC="../gx/2002/lglogo_200x41.png"
WIDTH="200" HEIGHT="41" border="0"></A>
<BR CLEAR="all">
<SMALL>...<I>making Linux just a little more fun!</I></SMALL>
</TD><TD WIDTH="380">
<CENTER>
<BIG><BIG><STRONG><FONT COLOR="maroon">Programming Bits: Meeting C# and Mono</FONT></STRONG></BIG></BIG>
<BR>
<STRONG>By <A HREF="../authors/ortiz.html">Ariel Ortiz Ramirez</A></STRONG>
</CENTER>
</TD></TR>
</TABLE>
<P>
<!-- END header -->
<p>C# (pronounced C-sharp) is a new object-oriented programming language
designed to take advantage of Microsoft's .NET development framework.
It has many similarities with other popular object-oriented languages such as
C++ and Java, yet it offers some new goodies.</p>
<p>Linux offers the opportunity to develop C# applications thanks to a project
called Mono. Mono is an open source implementation of the .NET platform. In the
following sections, I will describe the main elements of the current
implementation of the Mono system.</p>
<h2>The Mono Project</h2>
<p>At this time, Mono implements two standards: the C# programming language
(Standard ECMA-334) and the Common Language Infrastructure (Standard ECMA-335).
Both of these specifications were developed by Microsoft and submitted to ECMA
(a vendor consortium formerly known as the European Computer Manufacturers
Association) on October 2000. They were formally approved on December 2001, and
they will probably become ISO standards (thanks to a &quot;fast-track&quot;
agreement that ISO has with ECMA) some time before the end of next year.</p>
<p>The Mono project is sponsored by Ximian, the same company that brought us the
GNOME graphical desktop environment. Mexican hacker and Ximian CTO Miguel de
Icaza currently leads the development of this project. In my opinion, the people
involved with the development of Mono have done a remarkable job in quite a
short amount of time. By the way, the word &quot;Mono&quot; means monkey in
Spanish. These guys at Ximian really like monkeys.</p>
<h2>Hello Mono World!</h2>
<p>Lets follow a simple programming example in order to understand how C# and the
different Mono components fit together. To see this in action, make sure you
have a working Mono installation (see the <a href="#resources"> resources</a> section for information on
downloading and installing Mono).&nbsp;</p>
<p>The following figure summarizes the process we will follow in order to
compile and run our C# program:</p>
<img border="0" src="misc/ortiz/using_mono.png" alt="Compiling and running C# programs." width="390" height="351">
<p> First, we will create a simple C# source
program (the classical &quot;Hello World!&quot; couldn't be missing). Type the
following program using your favorite text editor and save the file as <b>hello.cs</b>:</p>
<blockquote>
<pre>
class Hello {
public static void Main() {
System.Console.WriteLine(&quot;Hello Mono World!&quot;);
}
}
</pre>
</blockquote>
<p>This program is composed of a class named <code>Hello</code> which contains
a method called <code>Main</code>. This method establishes the program entry
point, in the same way that the <code>main</code> function is the start of a
C/C++ program. In this example, the <code>Main</code> method prints to the
standard output the message &quot;Hello Mono World&quot;.</p> <p>We can now
compile the program using the Mono C# compiler, called <code>mcs</code>. At the
shell prompt type:</p>
<blockquote>
<pre>
mcs hello.cs
</pre>
</blockquote>
<p>We now should have a file called <b>hello.exe</b> in the current directory.
But don't get baffled about the .exe file name extension. It is not a Windows
executable file, at least not in the way we're used to. Contrary to what happens
when we compile a program written in languages like C or C++, the C# compiler
does not generate a machine-specific object file (for example a Linux ELF x86
object file), but instead generates a special binary file called an <b>assembly</b>,
which is made up of <b>metadata</b> and <b>intermediate language</b> (IL)
instructions. These two together represent a platform-agnostic translation of
the program source code. This means, of course, that when we actually run the
program contained in the assembly, its intermediate language code has to be translated
to the native code of the computer where the program is being run. This last
translation phase is carried out by a <b>virtual machine</b>, whose behavior is
defined by the <b>Common Language Infrastructure</b> (CLI) specification. The
CLI defines an object oriented runtime environment that supports a base class
library, dynamic class loading and linking, multiple thread execution,
just-in-time compilation, and automatic memory management. The
Microsoft implementation of the CLI specification is usually referred as the <b>Common
Language Runtime</b> (CLR). We say that the CLR is a superset of the CLI because
the CLR contains some extensions that are not part of the CLI.</p>
<p>To execute our assembly, we must invoke the program called <code>mono</code>,
which is the Mono virtual machine. Type at the shell prompt the following:</p>
<blockquote>
<pre>
mono hello.exe
</pre>
</blockquote>
<p>The output should be:</p>
<blockquote>
<pre>
Hello Mono World!
</pre>
</blockquote>
<h2>Behind the Scenes</h2>
<p>Lets see how to examine the contents of our assembly. The program <code>monodis</code>
(Mono disassembler) reads the binary information of an assembly and
produces a textual representation of its contents. Type at the shell prompt:</p>
<blockquote>
<pre>
monodis hello.exe
</pre>
</blockquote>
<p>The disassembler output should be something like the following:</p>
<blockquote>
<pre>
.assembly extern mscorlib
{
.ver 0:0:0:0
}
.assembly 'hello'
{
.hash algorithm 0x00008004
.ver 0:0:0:0
}
.class private auto ansi beforefieldinit Hello
extends [mscorlib]System.Object
{
// method line 1
.method public hidebysig specialname rtspecialname
instance default void .ctor() cil managed
{
// Method begins at RVA 0x20ec
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void valuetype [corlib]System.Object::.ctor()
IL_0006: ret
} // end of method instance default void .ctor()
// method line 2
.method public static
default void Main() cil managed
{
// Method begins at RVA 0x20f4
.entrypoint
// Code size 11 (0xb)
.maxstack 8
IL_0000: ldstr &quot;Hello Mono World!&quot;
IL_0005: call void class [corlib]System.Console::WriteLine(string)
IL_000a: ret
} // end of method default void Main()
} // end of type Hello
</pre>
</blockquote>
<p>The first part of this output corresponds to the metadata. It contains
information about the current version of the assembly, any optional security constraints,
locale information, and a list of all externally referenced assemblies that are
required for proper execution. The rest of the output represents the IL code. We
can spot two methods in this code: the default class constructor called <code>.ctor</code>,
provided automatically by the compiler, and our <code>Main</code> method. As
described before, when the virtual machine is asked to run this code, it uses a
just-in-time (JIT) compiler to translate the IL into the native machine code of the
hosting environment. The native code is not generated until it is actually
needed (thus the name just-in-time). For our example, the following is the native x86
machine code (in AT&amp;T assembly language syntax) that gets generated for the <code>Main</code>
method:</p>
<blockquote>
<pre>
push %ebp
mov %esp,%ebp
sub $0x30,%esp
push $0x80c9eb0
mov 0x805462c,%eax
push %eax
cmpl $0x0,(%eax)
mov (%eax),%eax
call *0x94(%eax)
add $0x8,%esp
mov 0x805462c,%eax
push %eax
cmpl $0x0,(%eax)
mov (%eax),%eax
call *0xb4(%eax)
add $0x4,%esp
leave
ret
</pre>
</blockquote>
<p>Mono also comes with an interpreter called <code>mint</code>. If you use this
program, the IL instructions are interpreted instead of being compiled to native
code by the JIT. Actually, our simple program might be a little bit faster when
run under <code>mint</code> because the JIT compiler will take some time to
compile the code of our program and store it some where in memory. Of course,
subsequent execution of the native code already in memory is definitely faster
than interpretation. Currently the Mono JIT compiler is only available for x86
machines. The Mono interpreter must be used in any non-x86 machine. To see the
interpreter running, type at the shell prompt:</p>
<blockquote>
<pre>
mint hello.exe
</pre>
</blockquote>
<p>If you're familiar with Java, you might be thinking that all this technology
sounds pretty much like the way that the Java platform works. And this is indeed
so. The CLI virtual machine is the key factor for platform independence. This
means that I can write and compile a program in Linux using Mono, and then run
it in a Windows computer with the .NET framework. There is no need to rewrite or
recompile the source code. But in contrast to the Java Virtual Machine, which is
tightly coupled to the Java programming language, the CLI specification not only
allows platform independence, it also allows language independence. Windows has
compilers that target the CLR from a number of languages. The most
important ones are part of Microsoft's Visual Studio .NET development
environment: Visual Basic .NET, JScript .NET, Managed C++ and C#. Other
languages supported, from third party vendors, include APL, COBOL, Eiffel,
Forth, Fortran, Haskell, Mercury, Mondrian, Oberon, Pascal, Perl, Python, RPG,
Scheme and SmallScript. The Mono project only has a C# compiler at this time, but we will probably
see in the near future other languages being supported.</p>
<p>Another important element of the CLI is the <b>Common Type System </b>(CTS).
The CTS fully describes all the data types supported by the virtual machine,
including how these data types interact with each other and how they are
represented as metadata inside the assemblies. It is important to note that not
all languages available for the CLI support all data types in the CTS. So there
is a <b>Common Language Specification</b> (CLS), that defines a subset of common
types that ensure that binary assemblies can be used across all languages that
target the CLI. This means that if we build a CLI class that only exposes CLS
compliant features, any CLI compatible language can use it. You could create a class in
Eiffel, subclass it in C# and instantiate it in a Visual Basic.NET program. Now
this is real language interoperability.</p>
<h2>Some Advantages</h2>
<p>Using a CLI compliant platform, such as Mono or the .NET framework, has some
important advantages:</p>
<ul>
<li>Programs can be run without recompiling on any operating system and
processor that supports the platform.</li>
<li>There is complete multiple language integration.</li>
<li>The system supports important security measures.</li>
<li>A common runtime engine is shared by all CLI aware languages.</li>
<li>A consistent object model is used by all CLI aware languages, including a standard
API offered by a single base class library. Once you learn this API, you can
use it in any language supported by the platform.</li>
<li>There is a simplified deployment model. There is no need to register a
binary unit into the system registry.&nbsp;</li>
<li>Multiple versions of the same binary library (DLL) can coexist in harmony
on the same computer.&nbsp;</li>
</ul>
<p> C#, as a programming language, has also some important features:</p>
<ul>
<li>It includes constructs such as properties, events and attributes that ease
the construction of software components.&nbsp;</li>
<li>It does not require the use separate header of interface definition
language (IDL) files.</li>
<li>It has a simplified versioning mechanism.</li>
<li>It's type safe and has a unified type system. All data types (including
primitive types) derive from a single base class.</li>
<li>It has automatic memory management, through the use of garbage collection.</li>
<li>It's closely integrated to the CLI.</li>
</ul>
<p>I will discuss these and other C# issues more thoroughly in later
articles.&nbsp;</p>
<h2><a name="resources">Resources</a></h2>
<dl>
<dt> <a href="http://www.go-mono.com/">http://www.go-mono.com/</a></dt>
<dd>The official Mono home page. The download and install instructions
can be found here.</dd>
<dt><a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dndotnet/html/deicazainterview.asp">http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dndotnet/html/deicazainterview.asp</a></dt>
<dd>A very interesting interview with Miguel de Icaza about the Mono project
and the use of ECMA standards.</dd>
<dt><a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cscon/html/vcoriCStartPage.asp">http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cscon/html/vcoriCStartPage.asp</a></dt>
<dd>Information on the C# programming language at MSDN.</dd>
<dt><a href="http://www.ecma.ch/ecma1/STAND/ecma-334.htm">http://www.ecma.ch/ecma1/STAND/ecma-334.htm</a></dt>
<dd>The Standard ECMA-334 C# Language Specification.</dd>
<dt><a href="http://www.ecma.ch/ecma1/STAND/ecma-335.htm">http://www.ecma.ch/ecma1/STAND/ecma-335.htm</a></dt>
<dd>The Standard ECMA-335 Common Language Infrastructure.</dd>
</dl>
<!-- *** BEGIN copyright *** -->
<hr>
<CENTER><SMALL><STRONG>
Copyright &copy; 2002, Ariel Ortiz Ramirez.
Copying license <A HREF="../copying.html">http://www.linuxgazette.com/copying.html</A><BR>
Published in Issue 84 of <i>Linux Gazette</i>, November 2002
</STRONG></SMALL></CENTER>
<!-- *** END copyright *** -->
<HR>
<!--startcut ==========================================================-->
<CENTER>
<!-- *** BEGIN navbar *** -->
<IMG ALT="" SRC="../gx/navbar/left.jpg" WIDTH="14" HEIGHT="45" BORDER="0" ALIGN="bottom"><A HREF="orr.html"><IMG ALT="[ Prev ]" SRC="../gx/navbar/prev.jpg" WIDTH="16" HEIGHT="45" BORDER="0" ALIGN="bottom"></A><A HREF="index.html"><IMG ALT="[ Table of Contents ]" SRC="../gx/navbar/toc.jpg" WIDTH="220" HEIGHT="45" BORDER="0" ALIGN="bottom" ></A><A HREF="../index.html"><IMG ALT="[ Front Page ]" SRC="../gx/navbar/frontpage.jpg" WIDTH="137" HEIGHT="45" BORDER="0" ALIGN="bottom"></A><A HREF="http://www.linuxgazette.com/cgi-bin/talkback/all.py?site=LG&article=http://www.linuxgazette.com/issue84/ortiz.html"><IMG ALT="[ Talkback ]" SRC="../gx/navbar/talkback.jpg" WIDTH="121" HEIGHT="45" BORDER="0" ALIGN="bottom" ></A><A HREF="../lg_faq.html"><IMG ALT="[ FAQ ]" SRC="./../gx/navbar/faq.jpg"WIDTH="62" HEIGHT="45" BORDER="0" ALIGN="bottom"></A><A HREF="qubism.html"><IMG ALT="[ Next ]" SRC="../gx/navbar/next.jpg" WIDTH="15" HEIGHT="45" BORDER="0" ALIGN="bottom" ></A><IMG ALT="" SRC="../gx/navbar/right.jpg" WIDTH="15" HEIGHT="45" ALIGN="bottom">
<!-- *** END navbar *** -->
</CENTER>
</BODY></HTML>
<!--endcut ============================================================-->