embedded-api 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. Embedding the Mono runtime, preliminary version
  2. Miguel de Icaza ([email protected]),
  3. Paolo Molaro ([email protected])
  4. This document describes how to embed the Mono runtime in your
  5. application, and how to invoke CIL methods from C, and how to
  6. invoke C code from CIL. Both the JIT and interpreter can be
  7. embedded in very similar ways so most of what is described
  8. here can be used in either case.
  9. * Embedding the runtime.
  10. Embedding the runtime consists of various steps:
  11. * Compiling and linking the Mono runtime
  12. * Initializing the Mono runtime
  13. * Optionally expose C code to the C#/CIL universe.
  14. These are discussed in detail next.
  15. ** Compiling and Linking
  16. To embed the runtime, you have to link your code against the
  17. Mono runtime libraries. To do this, you want to pass the
  18. flags returned by pkg-config to your compiler:
  19. pkg-config --cflags --libs mono
  20. is used to get the flags for the JIT runtime and
  21. pkg-config --cflags --libs mint
  22. for the interpreted runtime.
  23. Like this:
  24. gcc sample.c `pkg-config --cflags --libs mono`
  25. You can separate the compilation flags from the linking flags, for
  26. instance, you can use the following macros in your makefile:
  27. CFLAGS=`pkg-config --cflags mono`
  28. LDFLAGS=`pkg-config --libs mono`
  29. ** Initializing the Mono runtime
  30. To initialize the JIT runtime, call mono_jit_init, like this:
  31. #include <mono/mini/jit.h>
  32. MonoDomain *domain;
  33. domain = mono_jit_init ("domain-name");
  34. For the interpreted runtime use mono_interp_init instead:
  35. #include <mono/interpreter/embed.h>
  36. MonoDomain *domain;
  37. domain = mono_interp_init ("domain-name");
  38. That will return a MonoDomain where your code will be
  39. executed. You can create multiple domains. Each domain is
  40. isolated from the other domains and code in one domain will
  41. not interfere with code in other domains. This is useful if
  42. you want to host different applications in your program.
  43. Now, it is necessary to transfer control to Mono, and setup
  44. the threading infrastructure, you do this like this:
  45. void *user_data = NULL;
  46. mono_runtime_exec_managed_code (domain, main_thread_handler, user_data);
  47. Where your main_thread_handler can load your assembly and execute it:
  48. static void main_thread_handler (gpointer user_data)
  49. MonoAssembly *assembly;
  50. assembly = mono_domain_assembly_open (domain, "file.dll");
  51. if (!assembly)
  52. error ();
  53. In the above example, the contents of `file.dll' will be
  54. loaded into the domain. This only loads the code, but it will
  55. not execute anything yet. You can replace `file.dll' with
  56. another transport file, like `file.exe'
  57. To start executing code, you must invoke a method in the
  58. assembly, or if you have provided a static Main method (an
  59. entry point), you can use the convenience function:
  60. retval = mono_jit_exec (domain, assembly, argc - 1, argv + 1);
  61. or when using the interpreter use:
  62. retval = mono_interp_exec (domain, assembly, argc - 1, argv + 1);
  63. If you want to invoke a different method, look at the
  64. `Invoking Methods in the CIL universe' section later on.
  65. ** Shutting down the runtime
  66. To shutdown the Mono runtime, you have to clean up all the
  67. domains that were created, use this function:
  68. mono_jit_cleanup (domain);
  69. Or in the case of the interpreted runtime use:
  70. mono_interp_cleanup (domain);
  71. ** Applications that use threads.
  72. The Boehm GC system needs to catch your calls to the pthreads
  73. layer, so in each file where you use pthread.h you should
  74. include the <gc/gc.h> file.
  75. If you can not do this for any reasons, just remember that you
  76. can not store pointers to Mono Objects on the stack, you can
  77. store them safely in the heap, or in global variables though
  78. * Exposing C code to the CIL universe
  79. The Mono runtime provides two mechanisms to expose C code to
  80. the CIL universe: internal calls and native C code. Internal
  81. calls are tightly integrated with the runtime, and have the
  82. least overhead, as they use the same data types that the
  83. runtime uses.
  84. The other option is to use the Platform Invoke (P/Invoke) to
  85. call C code from the CIL universe, using the standard P/Invoke
  86. mechanisms.
  87. To register an internal call, use this call in the C code:
  88. mono_add_internal_call ("Hello::Sample", sample);
  89. Now, you need to declare this on the C# side:
  90. using System;
  91. using System.Runtime.CompilerServices;
  92. class Hello {
  93. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  94. extern static string Sample ();
  95. }
  96. Since this routine returns a string, here is the C definition:
  97. static MonoString*
  98. Sample ()
  99. {
  100. return mono_string_new (mono_domain_get (), "Hello!");
  101. }
  102. Notice that we have to return a `MonoString', and we use the
  103. `mono_string_new' API call to obtain this from a string.
  104. * Invoking Methods in the CIL universe
  105. Calling a method in the CIL universe from C requires a number of steps:
  106. * Obtaining the MonoMethod handle to the method.
  107. * The method invocation.
  108. ** Obtaining a MonoMethod
  109. To get a MonoMethod there are several ways.
  110. You can get a MonoClass (the structure representing a type)
  111. using:
  112. MonoClass *
  113. mono_class_from_name (MonoImage *image, const char* name_space, const char *name);
  114. and then loop in the returned class method array until you get
  115. the one you're looking for. There are examples of such
  116. searches as static functions in several C files in
  117. metadata/*.c: we need to expose one through the API and remove
  118. the duplicates.
  119. The other, simpler, way is to use the functions in
  120. debug-helpers.h: there are examples of their use in monograph,
  121. mint and the jit as well. You basically use a string
  122. description of the method, like:
  123. "System.Object:GetHashCode()"
  124. and create a MonoMethodDesc out of it with:
  125. MonoMethodDesc* mono_method_desc_new (const char *name, gboolean include_namespace);
  126. You can then use:
  127. MonoMethod* mono_method_desc_search_in_class (MonoMethodDesc *desc, MonoClass *klass);
  128. MonoMethod* mono_method_desc_search_in_image (MonoMethodDesc *desc, MonoImage *image);
  129. to search for the method in a class or in an image. You would
  130. tipically do this just once at the start of the program and
  131. store the result for reuse somewhere.
  132. ** Invoking a Method
  133. There are two functions to call a managed method:
  134. MonoObject*
  135. mono_runtime_invoke (MonoMethod *method, void *obj, void **params,
  136. MonoObject **exc);
  137. and
  138. MonoObject*
  139. mono_runtime_invoke_array (MonoMethod *method, void *obj, MonoArray *params,
  140. MonoObject **exc);
  141. obj is the 'this' pointer, it should be NULL for static
  142. methods, a MonoObject* for object instances and a pointer to
  143. the value type for value types.
  144. These functions can be used in both the JIT and the interpreted
  145. environments.
  146. The params array contains the arguments to the method with the
  147. same convention: MonoObject* pointers for object instances and
  148. pointers to the value type otherwise. The _invoke_array
  149. variant takes a C# object[] as the params argument (MonoArray
  150. *params): in this case the value types are boxed inside the
  151. respective reference representation.
  152. From unmanaged code you'll usually use the
  153. mono_runtime_invoke() variant.
  154. Note that this function doesn't handle virtual methods for
  155. you, it will exec the exact method you pass: we still need to
  156. expose a function to lookup the derived class implementation
  157. of a virtual method (there are examples of this in the code,
  158. though).
  159. You can pass NULL as the exc argument if you don't want to
  160. catch exceptions, otherwise, *exc will be set to the exception
  161. thrown, if any. if an exception is thrown, you can't use the
  162. MonoObject* result from the function.
  163. If the method returns a value type, it is boxed in an object
  164. reference.
  165. We have plans for providing an additional method that returns
  166. an unmanaged->managed thunk like this:
  167. void* mono_method_get_unmanaged_thunk (MonoMethod *method);
  168. You'll be able to store the returned pointer in a function
  169. pointer with the proper signature and call that directly from
  170. C:
  171. typedef gint32 (*GetHashCode) (MonoObject *obj);
  172. GetHashCode func = mono_method_get_unmanaged_thunk (System_Object_GetHashCode_method);
  173. gint32 hashvalue = func (myobject);
  174. It may not be possible to manage exceptions in that case,
  175. though. I need to think more about it.
  176. ** Threading issues
  177. If your application creates threads on its own, and you want them to
  178. be able to call code into the CIL universe with Mono, you have to
  179. register the thread with Mono before issuing the call.
  180. To do so, call the mono_thread_attach() function before you execute
  181. any managed code from the thread
  182. * Samples
  183. See the sample programs in mono/sample/embed for examples of
  184. embedding the Mono runtime in your application.