teste.c 1.8 KB

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