make your own site for free

Embedding Mono

How to execute binary code files with Mono


In this article we will explain the basic concepts you should know if you want to embed the Mono runtime into your C++ application.

Mono is a .NET based open source platform with a very useful CSharp compiler that we use to compile our scripts. If you want to know more about Mono, check this official link.

Before stating, download this prepared Visual Studio Solution. We will be commenting it below:

Mobirise

Includes

We will include the standard iostream library to print text on the console with std::cout.

The jit library is for the CSharp runtime itself, and the assembly is to setup our directories and load the binary code.

MAIN

Lets look at our main:

Mobirise

As you can see, we are dealing with a very little example here.
Lets comment the code:

1. mono_set_dirs(): This function notifies the library where are the /lib and /etc folders installed. If you want to download the code and see the results, you will have to change that to your locations.

2. mono_jit_init("Domain Name"): This function creates and initializes a MonoDomain*, where all the CSharp application will reside inside. The domain name can be whatever you want.

3. mono_domain_assembly_open(): This function creates and links an assembly (A CSharp ".exe" or ".dll" file) into the already created domain. Here is where our CSharp code is stored.

4. mono_add_internal_call(): This function links an extern-specified internal call in CSharp with a function pointer in the C++ universe. You can have as many as you want.

5. mono_jit_exec(): This function executes the main method contained in an Assembly. Note that a ".dll" cant have a main method, so this function will fail if you try.

With those explanation, you should now be able to understand what the 80% of the code does. As you can see it is very straight forward. Lets now look at the CSharp project:

CSHARP CODE

Mobirise

As you can see, here we are only defining the method we linked in C++ as an internal call and calling it in our main. Pretty simple.

Mobirise

The PrintMethod in C++

The only thing you must notice is that some objects are sent to C++ as some mono classes objects, and you must convert them, like our case with the string. Here you have all the necessary documentation.



If you want to try the code, recompile both projects and press f5.

Mobirise

Maintained by Jonathan Molina-Prados Ciudad

Alita Unbreakable Warrior