Enabled g_mem_set_vtable through the configure option --with-overridable-allocators...
[mono.git] / samples / embed / teste.c
1 #include <mono/jit/jit.h>
2 #include <mono/metadata/environment.h>
3 #include <mono/utils/mono-publib.h>
4 #include <stdlib.h>
5
6 /*
7  * Very simple mono embedding example.
8  * Compile with: 
9  *      gcc -o teste teste.c `pkg-config --cflags --libs mono-2` -lm
10  *      mcs test.cs
11  * Run with:
12  *      ./teste test.exe
13  */
14
15 static MonoString*
16 gimme () {
17         return mono_string_new (mono_domain_get (), "All your monos are belong to us!");
18 }
19
20 static void main_function (MonoDomain *domain, const char *file, int argc, char** argv)
21 {
22         MonoAssembly *assembly;
23
24         assembly = mono_domain_assembly_open (domain, file);
25         if (!assembly)
26                 exit (2);
27         /*
28          * mono_jit_exec() will run the Main() method in the assembly.
29          * The return value needs to be looked up from
30          * System.Environment.ExitCode.
31          */
32         mono_jit_exec (domain, assembly, argc, argv);
33 }
34
35 static int malloc_count = 0;
36
37 static void* custom_malloc(size_t bytes)
38 {
39         ++malloc_count;
40         return malloc(bytes);
41 }
42
43 int 
44 main(int argc, char* argv[]) {
45         MonoDomain *domain;
46         const char *file;
47         int retval;
48         
49         if (argc < 2){
50                 fprintf (stderr, "Please provide an assembly to load\n");
51                 return 1;
52         }
53         file = argv [1];
54
55         MonoAllocatorVTable mem_vtable = {custom_malloc};
56         mono_set_allocator_vtable (&mem_vtable);
57
58         /*
59          * Load the default Mono configuration file, this is needed
60          * if you are planning on using the dllmaps defined on the
61          * system configuration
62          */
63         mono_config_parse (NULL);
64         /*
65          * mono_jit_init() creates a domain: each assembly is
66          * loaded and run in a MonoDomain.
67          */
68         domain = mono_jit_init (file);
69         /*
70          * We add our special internal call, so that C# code
71          * can call us back.
72          */
73         mono_add_internal_call ("MonoEmbed::gimme", gimme);
74
75         main_function (domain, file, argc - 1, argv + 1);
76         
77         retval = mono_environment_exitcode_get ();
78         
79         mono_jit_cleanup (domain);
80
81         fprintf (stdout, "custom malloc calls = %d\n", malloc_count);
82
83         return retval;
84 }
85