teste.c 2.1 KB

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