How does Mono work - c#

I have used C# in Visual Studio with .NET, and I have played around a little with Mono on openSUSE Linux, but I don't really understand how it works.
If I write an app in Windows on .NET, how does this relate to Mono? I can't just execute an a Windows .exe file on Linux without Wine, so it doesn't help me execute apps developed in Windows.
Is the purpose purely to have a .NET library equivalent on Linux (and others) to make cross platform development easier? For example, if I was a business and wanted to reach Linux customers, but really wanted to use .NET, then Mono should be my choice? Or is there something more that I'm missing?

This is an old question (with an already selected answer) but I do not believe the question has really been answered well.
First, a little background...
How does .NET work?
A traditional Windows .EXE file is a binary file that represents a series of machine language instructions that your computer understands and that makes calls into the Win32 API which are parts of Windows that deliver services that applications can take advantage of. The machine language used is very specific to your kind of computer and the Win32 calls make the executable very dependent on Windows. A .NET executable is not like that.
It is important to realize that a .NET executable (.EXE file) is not actually a native Windows application. Windows itself does not understand how to run the code in a .NET executable. Your computer does not understand it either.
Much like Java, a .NET application is made up of instructions in a language called CIL (Common Intermediate Language) that you can think of as the machine language for an idealized computer that does not really exist. In .NET, the software implementation of this idealized machine is called the Common Language Runtime (CLR). The equivalent in the Java world is called the Java Virtual Machine (JVM). In Java, the equivalent to CIL is called Java bytecode. CIL is sometimes called MSIL (Microsoft Intermediate Language).
CIL is designed to run on the CLR (an idealized machine) but is otherwise platform independent, which means that the CIL does not care what kind of computer you have or what operating system you are running.
Just as you need a native version of the Java JVM on each platform on which you want to run Java, you need a native version of the CLR to run .NET CIL executables. The CLR is a native Windows application just like the traditional Win32 EXE files described above. The CLR itself is specific to the Windows implementation and computer architecture on which it was designed to run.
It does not matter what .NET language you start with (C#, VisualBasic, F#, IronPython, IronRuby, Boo, etc.), they all get compiled down to CIL bytecode. You can easily "disassemble" a CIL program into a form of object-oriented assembly language that is easily readable by humans. You can write a program in CIL directly yourself but few people do.
On Windows, the CLR compiles this CIL code Just-in-Time (JIT) right when you run the executable--just before the code is actually run. This means that the CIL bytecode is converted (compiled) to actual machine code that runs natively on your computer. This part of the CLR is called the JIT compiler or often just the JIT.
To date, Microsoft has released four versions of the CLR: 1.0, 1.1, 2.0, and 4.0. You need to have the right version of the CLR installed on your machine if you want to run .NET executables targeting that runtime. The CLR 2.0 supports .NET 2.0, 3.0, and 3.5 applications. For other versions of .NET, the .NET version maps cleanly to the CLR version.
In addition to the JIT/CLR, .NET provides a host of libraries (assemblies) that make up the rest of the .NET framework and that provide a host of capabilities and services that .NET applications can call upon. The great majority of these assemblies are pure CIL code which runs on the CLR. On Windows, a some make calls into the Win32 API as well. When you install .NET, you are installing the CLR, the class libraries (framework), and a bunch of development tools. Each version of the CLR generally requires a complete set of these "framework" assemblies. Some versions of .NET (eg. 3.0 and 3.5) added additional framework assemblies without updating the CLR or the existing assemblies associated with that CLR.
The Portable Executable (PE) file format that a Windows .EXE file is delivered in contains a header that describes the executable and identifies the file as a .NET file or a native Win32 file. When Windows tries to run a .NET file, it sees this header and automatically invokes the CLR on your behalf. This is why .NET EXE files appear to run natively on Windows.
Ok, so how does Mono work?
Mono implements the CLR on Linux, Mac, and other platforms. The Mono runtime (the CLR) is a native application written mostly in the C language and compiled down to machine language code for the computer system on which is designed to run. Like on Windows, the Mono runtime is specific to the Operating System and kind of machine you are using.
Just like on Windows, the Mono runtime (the CLR) compiles the CIL bytecode in your .NET executable Just-in-time to native code that your computer can understand and execute. In this way, a .NET file is just as "native" to Linux as it is to Windows.
To port Mono to a new architecture you need to port the JIT/CLR. This is just like porting any native application to a new platform.
How well .NET code runs on Linux or Mac is really just a question of how well the CLR is implemented on these systems. In theory, the Mono CLR could execute .NET code on these systems much better than the MS version of .NET does on Windows. In practice, the MS implementation is generally superior (though not in all cases).
In addition to the CLR, Mono provides most of the rest of the libraries (assemblies) that make up the .NET framework. Just as with the Microsoft version of .NET (in fact more so) the Mono assemblies are provided as CIL bytecode. This makes it possible to take a *.dll or *.exe file from Mono and run it unmodified on Windows, Mac, or Linux as CIL is the "native" language of the CLR implementations on these systems.
Just like on Windows, Mono supports multiple versions of the CLR and the associated assemblies:
Very early versions of Mono (before 1.2?) only supported CLR 1.0 or 1.1.
Mono did not support big chunks of the 2.0 framework until it's own 2.0 version.
Mono versions up to version 2.4 supported both CLR 1.1 and CLR 2.0 applications.
Starting with Mono 2.6, CLR 4.0 was added but CLR 2.0 was still the default.
Starting with Mono 2.8 the CLR 4.0 became the default and the CLR 1.1 is no longer supported.
Mono 2.10 continues to use the CLR 4.0 as default and also to support the CLR 2.0.
Just like the real .NET (but in far fewer cases) there are some Mono assemblies that call into native libraries. In order to make the System.Drawing assembly work on Mono, the Mono team wrote a Linux program to simulate the GDI+ portion of the Win32 API on Linux. This library is called 'libgdiplus'. If you compile Mono from source, you will notice that you need to build this 'libgdiplus' file before you can build 'mono'. You do not need 'libgdiplus' on Windows because the GDI+ portion of the Win32 API is already part of Windows. A full port of Mono to new platforms requires this 'libgdiplus' library to be ported as well.
In areas where the design of the .NET library is overly influenced by the design of Windows, and a poor fit for systems like Mac or Linux, the Mono team has written extensions to the .NET framework. The Mono extensions are also just CIL bytecode and generally work just fine on .NET.
Unlike on Windows, Linux generally does not detect .NET executables and launch the CLR by default. The user must usually run the CLR directly by typing 'mono appname.exe' or something similar. Here 'mono' is the application that implements the CLR and 'appname.exe' is the EXE file that contains the .NET code to be executed.
To make things easier for users, Mono applications are often wrapped in a shell script that launches the CLR. This hides the fact that the CLR is being used just as in Windows. It is also possible to tell Linux to launch the CLR when a file using the PE file format is encountered. This is usually not done as the PE file format is also used for native Win32 Windows executables which of course the CLR (Mono) does not support.
There is no technical reason why a PE launcher could not be used by Linux which then launches either a system that understands native Windows code (like Wine) or the CLR (Mono) as appropriate. This has simply not been done to my knowledge.
Back and forth
Any .NET code that sticks to "fully managed" code, which means it does not call into non-.NET code, should work fine on Mono on all platforms. I routinely use compiled .NET assemblies from Windows (for which I do not have the code) on Linux and Mac.
I can also take any code that I compile on Mono and run that on .NET on Windows. I can provide a client some code I compiled with Mono and not worry if he is on 32-bit or 64-bit Windows for example. The client does need to have the right version of .NET (the right CLR) installed fo course. CLR 2.0 has been around for a very long time and you can bet almost all Windows users have it installed. The Mono compilers and other code are also just CIL executables and so they run fine on Windows if you like.
Mono compatibility is good enough that large chunks of actual Microsoft code, like ASP.NET MVC, can be taken (where legal to do so) from the actual MS version of .NET and run on Mac or Linux. In general, the Mono team has done a great job of implementing both the CLR and the rest of the framework (class libraries/assemblies).
ASP.NET
On Windows, the Internet Information Server (IIS) knows how to call into the CLR to execute .NET as part of a web application. On Linux/Mac there is an Apache module (mod_mono) that provides similar capabilities to the Apache webserver. This application is written in C and must also be ported to new architectures.
Porting Mono
This discussion has identified parts of Mono that are built as "native" executables and must exist on a system on which you want to run .NET applications.
The CLR (including JIT compiler) - generally known as Mono
libgdiplus (for systems which do not natively support the GDI+ API [only Windows does])
mod_mono (to allow Apache to invoke the CLR for .NET web applications)
These three components, with the addition of the class libraries, provide a .NET environment that looks "native" to the .NET executable files you need to run.
That is how Mono works.

A Windows EXE contains multiple "parts". Simplified, the .net Code (=MSIL) is only a Part of the EXE, and there is also a "real" native Windows Part inside the EXE that serves as some sort of launcher for the .net Framework which then executes the MSIL.
Mono will just take the MSIL and execute it, ignoring the native Windows Launcher stuff.
Again, this is a simplified overview.
Edit: I fear my understanding of the deep deep details is not good enough for really much detail (I know roughly what a PE Header is, but not really the details), but i found these links helpful:
NET Assembly Structure – Part II
.NET Foundations - .NET assembly structure

You can in fact run a .NET .exe file with Mono on Linux. This does not require Wine. In fact, Mono compiles programs to .exe files, which can run either with Mono on Linux or as an executable on Windows.

Mono is an open-source implementation of Microsofts .NET CLR (Common Language Runtime). This is what runs part of .NET programs which are not in native code but in CIL (Common Intermediate Language), a language and machine-neutral intermediate language. The Runtime takes that intermediate code and translates it into machine code.
At the current state of Mono, you can take .NET programs that use the main parts of .NET (mscorlib.dll) and run them everywhere Mono runs, not just Windows.

But as it is mentioned that Mono is open source and you can't just rely that it will be the full .NET implementation, it has some controls that are not working, you must be also careful with P/Invokes that your application will use, for e.g your application will communicate with MCI (Multimedia Controller Interface) under win32. But I was using mono writing GTK# Applications also, but I've also used my Windows applications that worked without any recompilation as mentioned our fellow programmers above, that is, mono is an open source alternative of Microsoft's .NET, and by default if you are building either WinForms or Gtk# applications mono will compile and will create an .exe assembly for each file, and of course if you want it will create an Dynamic Link Library (DLL), almost as it is done in .NET. Just for suggestion try writing some Gtk# (with MonoDevelop IDE which has its built-in gui designer called stetic). And of course mono can be a great replacement for Web Services that you can create them on .NET and you can host them on Apache (because Linux hosting nowadays are more cheap than Windows ones) web services and other asp.net apps will work under apache with a mod_mono module that must be included in apache.
A little bit out of topic but I just wanted to tell you a sneak-peek from my experience.

Also you can take a look to MoMA (if your goal is to port applications from Win to Lin).
The Mono Migration Analyzer (MoMA)
tool helps you identify issues you may
have when porting your .Net
application to Mono. It helps pinpoint
platform specific calls (P/Invoke) and
areas that are not yet supported by
the Mono project.
MoMA
Here is a webapp that compares the types of the BCL already implemented by Mono and the .NET Framework 3.5
http://mono.ximian.com/class-status/2.0-vs-3.5/index.html

To further Michael's response, I believe you will have to recompile on Mono for the app to run on the Mono runtime. Exceptions may exist. I've only played around with Mono just a bit, and I've always re-compiled the source. I've never tried to run a .NET app directly on Mono.
Also, Mono 1.9 is supposed to be fully .NET 2.0 compliant. Mono Olive and Moonlight are supposed to add .NET 3.0 (less WPF) and Silverlight functionality.

It might help you, How does Mono's C# compiler work? and as well as Understanding Mono C# Compiler book.

Related

Running winform application without .net framework

am developing a flash copy protect software with c#. The software is to remain on the flash drive(can not be transfered out or installed in the computer), it is a click and run software, no installation. I know that for it to work on other computers, the computer must have .net framework installed in it. I was thinking if it can be possible to add .net framework dll to the startup path of the application. If it will work, pls let me know and how to do it.
If there are other methods besides switching my project to C or C++, pls let me know. Thanks.
In normal .NET compilation (regardless of source language), the product is a (MS)IL - (Microsoft) Intermediate Language - dll. In case of executeables, it is given some native bootstrap code, a entry point, but it is still stricly tied to the Framework installation and works for nearly everything like a .NET dll. The Framework has to do the final IL -> Native Code translation. IL is a concept very similar to Java Bytecode, but with about 5 years of what works and does not work in Java.
.NET Native does not compile IL. It compiles hard, native code. Similar to the one any Native C++ (not to be mistaken with C++ .NET) compiler would make. The same a Delphi compiler would make. The same the Framework itself is written in. The final programm will have local copies of all the .NET .dll's it accesses. It is fully independant of any .NET Framework installation.

Using C DLL in MonoTouch and MonoDroid

I am new to using .NET, but I am interested in using MonoTouch/Droid to write mobile applications that could share some core code.
I have many C style API libraries I wish to use, for example libxml2. How do I call these native library methods in Mono? Can I use the same binaries compiled from Windows if I am developing in Windows? Can I use the Windows binaries if I am developing in OS X?
How do I call these native library methods in Mono?
You use p/invoke (platform invoke) to call native C code from any .NET language. You need to write those declarations (of find someone who did it before you) to use the native libraries. Like #Marcelo commented there are often very good, much easier to use .NET alternatives to most C libraries.
This will work on MonoTouch too. However you'll need provide a static library (.a on OSX, like a .lib on Windows) since Apple iOS does not allow linking with user-provided dynamic libraries (.dylib on OSX/iOS and .dll on Windows).
Can I use the same binaries compiled from Windows if I am developing in Windows?
Windows produced binaries should run fine with Mono on Windows. You can use Microsoft .NET on Windows too.
Can I use the Windows binaries if I am developing in OS X?
If the binaries are .NET compiled code then yes - as long as your p/invoke declrations are portable (e.g. 32 vs 64 bits types).
If the binaries are native code then no. Remember that Mono is not a Windows emulator. It runs CIL code, inside .EXE or .DLL, but it won't run native Windows code or provide access to Windows native API (outside Windows).

CLR IN MOBILE ----is it possible to use virtual machine on mobile os

as jvm makes java as plateform independent is it possible with CLR to make .net framework supported languages like c# plateform independent on mobile
Yes, you can use the Mono CLR. Mono is the open source implementation of C#, .NET BCL and the CLR.
MonoTouch runs on the iPhone
MonoDroid runs on Android devices
Yes-ish. At the tooling level, see MonoDroid, MonoTouch or the WP7 tools. However, in each case you are using the language to target a specific mobile platform. You may need different UI code for each, even if the core code is shared.
.NET Compact Framework works on mobile devices (and has for about 8 years now). .NET is also cross-platform (kind of) through the Mono and MonoTouch projects.
Technically, yes, but each handset has it's own limitations that may not make it very feasible.
If you look at the mono-project, it's a portable implementation of the CLR which can target mobile architectures, but it's still an area of development and not very mature yet.
MonoDroid is the project targetting Android handsets, but it's in a beta stage at the moment.
MonoTouch can target iOS, but it cannot take full advantage of the framework. Apple's licensing prevents virtual machines from running on the iOS, so .NET applications need to be AOT (Ahead-of-time) compiled to run on it. This works, but you won't be able to use parts of the BCL like the reflection API.
There's some early development for mono to support WebOS (Palm) too.

Converting .NET App to x86 native code

There's a program written entirely in C# that targets .NET Framework 2.0.
Is there a way I could somehow compile (translate) managed EXE to a native one so it could be .NET-agnostic? I know there are probably commercial products for that purpose... but they are a bit expensive.
The problem is that we are to deploy the program on computers running Windows XP with no .NET Framework installed. There's also a requirement that the program's size must not exceed 500Kb (1Mb maximum) for it is downloaded from the web server (now the size is 255Kb). That is why there's no way we could attach a full-fledged .NET FX (or even a reduced one) to the downloaded program's file.
Obviously it is a terrible software engineering error that should have been detected and avoided earlier so we could use native technologies like C++ instead.
We have tried for now Novell's Mono - an open-source implementation of .NET Framework for Linux, MAC and Windows. Mono consists of C# Compiler, IDE, runtime (CLR) and Class Library assemblies (like System.dll and mscorlib.dll - much like .NET's class library assemblies installed to GAC).
What we tried to do is to locate CLR files and ship those along with our program's file and a few assemblies. This way the program can be invoked by running "mono program.exe" (command prompt) on a user's computer.
In addition to the inconvenience of such a use for the end user CLR files (mono.exe and mono.dll) turned out to be about 2.5 Mb in total that is much greater than the desired 500 Kb or even 1 Mb.
So, we have left with no other option but to translate our .NET App to a native one by a compiler, however the question remains - what compiler should we use and where could we find one...
For now I have stumbled upon a Singularity OS Project by Microsoft Research. It is an open-source research OS that is written in managed code (in part at least). The Singularity OS includes a Bartok compiler that the OS uses in order to translate a managed program to a native one (x86 32 bit). It should be noted that Bartok can't translate all the aspects of .NET 2.0 to a native code, but most of them. However I haven't yet learnt how to use the Singularity...
I would be really grateful to you if you could provide me with some useful tips and advice regarding the problem, your own experience with Singularity OS and Bartok Compiler or another approaches to the problem that I have overlooked and ways of solving it.
Thank you very much in advance!
Finally, using Mono's Full AOT feature (on Callum Rogers' advice) I've managed to produce a program.exe.dll that lacks a CLI header.
So it looks to me like a native dll. However I can't figure out how to convert that dll into exe or make it operational.
Also this dll doesn't seem to expose any functions of interest such as main function.
Check out AOT (Ahead Of Time) Compilation from the Mono project. This compiles your managed project into a native exe or an elf executable (depending on which system you target) that does not need the JIT. This is the technique used to get mono apps onto the iPhone (where the JIT/Framework are not allowed) and also has the added benefits of faster startup times, lower memory usage and it makes it harder for people to decompile your code. You said you were already using Mono, so it should be compatible.
Read up about it at the mono-project.com website and at Miguel de Icaza's blog (and iPhone info).
Note that you cannot use dynamic code or generic interfaces like
interface IFoo<T> {
...
void SomeMethod ();
}
And you will have to compile the DLLs of all the libraries you use.
PS: Make sure to use "Full" AOT for your problem.
2018 Update
At Build 2018, Microsoft announced .Net Core 3.0 roadmap that support Windows desktop applications (Winform & WPF)
2017 Update
For console apps, you can use .net core Self-contained deployments (SCD). Even for a hello world app, your package will 50MB+. You still need to install VC runtime though.
Update
As #jenix's comment, .NET Native is only for Windows Store Apps(UWP). After 3 years of it's announcement, this is still true, .net native for desktop may be dropped by microsoft . So this answer is not applicable anymore.
========
Microsoft Announced .NET Native Preview on Build 2014
With the .NET Native Developer Preview, apps will get deployed on end-user devices as fully self-contained natively compiled code, and will not have a dependency on the .NET Framework on the target device/machine. So, no .NET framework required on the target machine with .NET Native.
Announcing .NET Native Preview
Microsoft .NET Native
There is a project called CrossNet that parses .Net Assemblies and generates unmanaged C++ code, that can be compiled in any standard compiler.
Not really a solution for .NET to native conversion, but maybe this helps: http://www.yoda.arachsys.com/csharp/faq/#framework.required
Not quite sure that there is much you can do besides painstakingly rewrite the application. To ease the already burdening process, you could disassemble the .NET application using something like Reflector (into Microsoft C++), and use that as a base to start and just replace managed C++ references with native ones.

Can you compile C# so it doesn't need the .NET Framework at runtime?

Is it possible to force the C# compiler to pull all the referenced calls out of the framework and pack them into dlls or even a single executable?
I like writing quick 'one-off' applications with C#, however I don't want to have to install the whole framework on the target machine once it's ready to go.
You ask a loaded question. C# is merely a language and does not require the .NET Framework. The process of compiling it requires a compiler, which may or may not itself take a dependency on the .NET Framework (Microsoft's C# compiler does not -- it is written in native code). Your program will need to reference some assembly where types, classes, and methods can be found for your use. You can remove system.dll and mscorlib.dll from your references list and reference your own assemblies. So you can avoid dependencies on the .NET Framework if you really work at it. But in the end, unless you have a C# compiler that compiles programs to native code you still have a dependency on the CLR.
That's a very technical way of saying... almost nothing. But it answers your question. :) More practically useful however is how to get your C# programs to run with a minimum of dependencies. mkbundle from mono will actually let you compile it all into an .exe with virtually no dependencies.
But if you want to stick with the Microsoft .NET Framework, you can achieve a much lighter footprint and faster install of the dependencies you commonly need by using the Client profile of .NET 3.5 SP1. You can read about it here:
http://msdn.microsoft.com/en-us/library/cc656912.aspx
Look at mkbundle using Mono.
It is now possible to compile C# to native code using Microsoft .NET Native:
https://msdn.microsoft.com/en-us/library/dn584397(v=vs.110).aspx
It automatically compiles the release version of apps that are written in managed code (C# or Visual Basic) and that target the .NET Framework and Windows 10 to native code.
...
For users of your apps, .NET Native offers these advantages:
•Fast execution times
•Consistently speedy startup times
•Low deployment and update costs
•Optimized app memory usage
This only works with Visual Studio .NET 2015.
Take a look at the .NET client profile.
This will allow you to package a minimum install on the client machine.. which will later be updated by windows update to the full framework.
This depends, of course, on your app only using libraries that are contained in the client profile ...
Some info here: http://blogs.windowsclient.net/trickster92/archive/2008/05/21/introducing-the-net-framework-client-profile.aspx
It's said it is possible, using 3rd-party tools such as http://www.remotesoft.com/linker/
Not possible. Your "compiled" C# application is a language which the .Net CLR interprets (should have said JITed, Reads the IL, compiles to native code, and then invokes the compiled native code) at runtime.
FYI .net 2.0 is a standard install on xp SP2 and vista, so you won't be paying that much of a penalty.
You could look into mono, but this still involves running some kind of framework on your target machine.
This dependency which unfortunately frequently breaks or is missing in the real world is a big reason why C# has not had a wider adoption. On the flip side most development does have dependencies.. look at C++ & Java for example.
I don't think we will really get away from these dependency issues anytime soon, so I recommend that if you want to use C#, that you make a wrapper for installation which checks for the .net framework version dependency you need, and if missing notify the user that they need this to run your app.
Some C# features are bound to interfaces of the .NET framework.
For example:
yield return requires the IEnumerable interface
using (x) {} requires the IDisposable interface

Categories

Resources