mono-api-embedding.html

## Embedding Mono

The Mono runtime can be embedded into C and C++ applications. Your C/C++ code can invoke managed code running in the Mono/.NET world and you can also surface your internal application APIs to Mono and .NET.

For an overview of how to embed Mono into your application and the strategies that you can use to embed Mono, check the Mono website's Embedding Mono page.

This page is the companion API reference for the above guide.

The simplest way of embedding Mono is illustrated here:

    int main (int argc, char *argv)
    {
    	/*
    	 * Load the default Mono configuration file, this is needed
    	 * if you are planning on using the dllmaps defined on the
    	 * system configuration
    	 */
    	mono_config_parse (NULL);

    	/*
    	 * mono_jit_init() creates a domain: each assembly is
    	 * loaded and run in a MonoDomain.
    	 */
    	MonoDomain *domain = mono_jit_init ("startup.exe");

    	/*
    	 * Optionally, add an internal call that your startup.exe
    	 * code can call, this will bridge startup.exe to Mono
    	 */
    	mono_add_internal_call ("Sample::GetMessage", getMessage);

    	/*
    	 * Open the executable, and run the Main method declared
    	 * in the executable
    	 */
    	MonoAssembly *assembly = mono_domain_assembly_open (domain, "startup.exe");

    	if (!assembly)
    		exit (2);
    	/*
    	 * mono_jit_exec() will run the Main() method in the assembly.
    	 * The return value needs to be looked up from
    	 * System.Environment.ExitCode.
    	 */
    	mono_jit_exec (domain, assembly, argc, argv);
    }

    /* The C# signature for this method is: string GetMessage () in class Sample */
    MonoString*
    getMessage ()
    {
    	return mono_string_new (mono_domain_get (), "Hello, world");
    }

`mono_jit_init`
Syntax
MonoDomain* mono_jit_init (const char *file)

`mono_jit_parse_options`
Syntax
void mono_jit_parse_options (int argc, char * argv[])

Description

Process the command line options in argv as done by the runtime executable. This should be called before `mono_jit_init`.
`mono_jit_exec`
Syntax
int mono_jit_exec (MonoDomain *domain, MonoAssembly *assembly, int argc, char *argv[])

Parameters

assembly | reference to an assembly
argc | argument count
argv | argument vector

Description
Start execution of a program.
`mono_set_dirs`
Syntax
void mono_set_dirs (const char *assembly_dir, const char *config_dir)

Parameters

assembly_dir | the base directory for assemblies
config_dir | the base directory for configuration files

Description

This routine is used internally and by developers embedding the runtime into their own applications.

There are a number of cases to consider: Mono as a system-installed package that is available on the location preconfigured or Mono in a relocated location.

If you are using a system-installed Mono, you can pass `NULL` to both parameters. If you are not, you should compute both directory values and call this routine.

The values for a given PREFIX are:

assembly_dir: PREFIX/lib config_dir: PREFIX/etc

Notice that embedders that use Mono in a relocated way must compute the location at runtime, as they will be in control of where Mono is installed.
`mono_parse_default_optimizations`
Syntax
int mono_parse_default_optimizations (const char* p)

`mono_runtime_set_main_args`
Syntax
int mono_runtime_set_main_args (int argc, char* argv[])

Parameters

argc | number of arguments from the command line
argv | array of strings from the command line

Description
Set the command line arguments from an embedding application that doesn't otherwise call `mono_runtime_run_main`.
`mono_jit_cleanup`
Syntax
void mono_jit_cleanup (MonoDomain *domain)

`mono_jit_set_trace_options`
Syntax
gboolean mono_jit_set_trace_options (const char* options)

Parameters

options | string representing the trace options

Return value
`TRUE` if the options were parsed and set correctly, `FALSE` otherwise.
Description
Set the options of the tracing engine. This function can be called before initializing the mono runtime. See the --trace mono(1) manpage for the options format.

### Internal Calls

The Mono runtime provides two mechanisms to expose C code to the CIL universe: internal calls and native C code. Internal calls are tightly integrated with the runtime, and have the least overhead, as they use the same data types that the runtime uses.

The other option is to use the Platform Invoke (P/Invoke) to call C code from the CIL universe, using the standard P/Invoke mechanisms.

To register an internal call, use this call you use the `mono_add_internal_call` routine.
`mono_add_internal_call`
Syntax
void mono_add_internal_call (const char *name, gconstpointer method)

Parameters

name | method specification to surface to the managed world
method | pointer to a C method to invoke when the method is called

Description

This method surfaces the C function pointed by method as a method that has been surfaced in managed code with the method specified in name as an internal call.

Internal calls are surfaced to all app domains loaded and they are accessibly by a type with the specified name.

You must provide a fully qualified type name, that is namespaces and type name, followed by a colon and the method name, with an optional signature to bind.

For example, the following are all valid declarations:

`MyApp.Services.ScriptService:Accelerate`

`MyApp.Services.ScriptService:Slowdown(int,bool)`

You use method parameters in cases where there might be more than one surface method to managed code. That way you can register different internal calls for different method overloads.

The internal calls are invoked with no marshalling. This means that .NET types like `System.String` are exposed as `MonoString*` parameters. This is different than the way that strings are surfaced in P/Invoke.

For more information on how the parameters are marshalled, see the Mono Embedding page.

See the Method Description reference for more information on the format of method descriptions.

### P/Invoke with embedded applications

Unlike internal calls, Platform/Invoke is easier to use and more portable. It allows you to share code with Windows and .NET that have a different setup for internal calls to their own runtime.

Usually P/Invoke declarations reference external libraries like:

    	[DllImport ("opengl")]
    	void glBegin (GLEnum mode)

Mono extends P/Invoke to support looking up symbols not in an external library, but looking up those symbols into the same address space as your program, to do this, use the special library name "__Internal". This will direct Mono to lookup the method in your own process.

There are situations where the host operating system does not support looking up symbols on the process address space. For situations like this you can use the mono_dl_register_library.

#### mono_dl_register_library

### Data Marshalling

Managed objects are represented as `MonoObject*` types. Those objects that the runtime consumes directly have more specific C definitions (for example strings are of type `MonoString *`, delegates are of type `MonoDelegate*` but they are still `MonoObject *`s).

As of Mono 1.2.x types defined in mscorlib.dll do not have their fields reordered in any way. But other libraries might have their fields reordered. In these cases, Managed structures and objects have the same layout in the C# code as they do in the unmanaged world.

Structures defined outside corlib must have a specific StructLayout definition, and have it set as sequential if you plan on accessing these fields directly from C code.

Important Internal calls do not provide support for marshalling structures. This means that any API calls that take a structure (excluding the system types like int32, int64, etc) must be passed as a pointer, in C# this means passing the value as a "ref" or "out" parameter.

### Mono Runtime Configuration

Certain features of the Mono runtime, like DLL mapping, are available through a configuration file that is loaded at runtime. The default Mono implementation loads the configuration file from `$sysconfig/mono/config` (typically this is `/etc/mono/config`).

See the `mono-config(5)` man page for more details on what goes in this file.

The following APIs expose this functionality:
`mono_config_cleanup`
Syntax
void mono_config_cleanup (void)

`mono_config_is_server_mode`
Syntax
mono_bool mono_config_is_server_mode (void)

`mono_config_parse`
Syntax
void mono_config_parse (const char *filename)

Parameters

filename | the filename to load the configuration variables from.

Description
Pass a `NULL` filename to parse the default config files (or the file in the `MONO_CONFIG` env var).
`mono_config_parse_memory`
Syntax
void mono_config_parse_memory (const char *buffer)

Parameters

buffer | a pointer to an string XML representation of the configuration

Description
Parses the configuration from a buffer
`mono_config_set_server_mode`
Syntax
void mono_config_set_server_mode (mono_bool server_mode)

`mono_config_string_for_assembly_file`
Syntax
const char * mono_config_string_for_assembly_file (const char *filename)

`mono_get_config_dir`
Syntax
const char* mono_get_config_dir (void)

`mono_get_machine_config`
Syntax
const char * mono_get_machine_config (void)

`mono_register_machine_config`
Syntax
void mono_register_machine_config (const char *config_xml)

`mono_set_config_dir`
Syntax
void mono_set_config_dir (const char *dir)

Description
Invoked during startup

### Advanced Execution Setups

These are not recommended ways of initializing Mono, they are done internally by mono_jit_init, but are here to explain what happens internally.
`mono_runtime_exec_managed_code`
Syntax
void mono_runtime_exec_managed_code (MonoDomain *domain, MonoMainThreadFunc main_func, gpointer main_args)

Parameters

domain | Application domain
main_func | function to invoke from the execution thread
main_args | parameter to the main_func

Description
Launch a new thread to execute a function

main_func is called back from the thread with main_args as the parameter. The callback function is expected to start `Main` eventually. This function then waits for all managed threads to finish. It is not necessary anymore to execute managed code in a subthread, so this function should not be used anymore by default: just execute the code and then call mono_thread_manage().
`mono_runtime_exec_main`
Syntax
mono_runtime_exec_main

`mono_init`
Syntax
MonoDomain* mono_init (const char *domain_name)

Return value
the initial domain.
Description

Creates the initial application domain and initializes the mono_defaults structure.

This function is guaranteed to not run any IL code. The runtime is initialized using the default runtime version.

`mono_init_from_assembly`
Syntax
MonoDomain* mono_init_from_assembly (const char *domain_name, const char *filename)

Parameters

domain_name | name to give to the initial domain
filename | filename to load on startup

Return value
the initial domain.
Description

Used by the runtime, users should use mono_jit_init instead.

Creates the initial application domain and initializes the mono_defaults structure. This function is guaranteed to not run any IL code. The runtime is initialized using the runtime version required by the provided executable. The version is determined by looking at the exe configuration file and the version PE field)

`mono_init_version`
Syntax
MonoDomain* mono_init_version (const char *domain_name, const char *version)

Return value
the initial domain.
Description

Used by the runtime, users should use `mono_jit_init` instead.

Creates the initial application domain and initializes the `mono_defaults` structure.

This function is guaranteed to not run any IL code. The runtime is initialized using the provided rutime version.

`mono_jit_exec`
Syntax
int mono_jit_exec (MonoDomain *domain, MonoAssembly *assembly, int argc, char *argv[])

Parameters

assembly | reference to an assembly
argc | argument count
argv | argument vector

Description
Start execution of a program.
`mono_jit_set_aot_mode`
Syntax
void mono_jit_set_aot_mode (MonoAotMode mode)

`mono_set_break_policy`
Syntax
void mono_set_break_policy (MonoBreakPolicyFunc policy_callback)

Parameters

policy_callback | the new callback function

Description

Allow embedders to decide whether to actually obey breakpoint instructions (both break IL instructions and `Debugger.Break` method calls), for example to not allow an app to be aborted by a perfectly valid IL opcode when executing untrusted or semi-trusted code.

policy_callback will be called every time a break point instruction needs to be inserted with the method argument being the method that calls `Debugger.Break` or has the IL `break` instruction. The callback should return `MONO_BREAK_POLICY_NEVER` if it wants the breakpoint to not be effective in the given method. `MONO_BREAK_POLICY_ALWAYS` is the default.
`mono_get_runtime_build_info`
Syntax
char* mono_get_runtime_build_info (void)

Return value
the runtime version + build date in string format.
Description
The returned string is owned by the caller. The returned string format is `VERSION (FULL_VERSION BUILD_DATE)` and build date is optional.

### Signal Chaining

`mono_set_signal_chaining`
Syntax
void mono_set_signal_chaining (gboolean chain_signals)

Description

Enable/disable signal chaining. This should be called before `mono_jit_init`. If signal chaining is enabled, the runtime saves the original signal handlers before installing its own handlers, and calls the original ones in the following cases: - a `SIGSEGV` / `SIGABRT` signal received while executing native (i.e. not JITted) code. - `SIGPROF` - `SIGFPE` - `SIGQUIT` - `SIGUSR2` Signal chaining only works on POSIX platforms.