test-invoke.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. #include <mono/jit/jit.h>
  2. #include <mono/metadata/environment.h>
  3. #include <mono/metadata/assembly.h>
  4. #include <mono/metadata/debug-helpers.h>
  5. #include <string.h>
  6. #include <stdlib.h>
  7. /*
  8. * Simple mono embedding example.
  9. * We show how to create objects and invoke methods and set fields in them.
  10. * Compile with:
  11. * gcc -Wall -o test-invoke test-invoke.c `pkg-config --cflags --libs mono` -lm
  12. * mcs invoke.cs
  13. * Run with:
  14. * ./test-invoke invoke.exe
  15. */
  16. static void
  17. access_valuetype_field (MonoObject *obj)
  18. {
  19. MonoClass *klass;
  20. MonoClassField *field;
  21. int val;
  22. klass = mono_object_get_class (obj);
  23. /* Now we'll change the value of the 'val' field (see invoke.cs) */
  24. field = mono_class_get_field_from_name (klass, "val");
  25. /* This time we also add a bit of error checking... */
  26. if (!field) {
  27. fprintf (stderr, "Can't find field val in MyType\n");
  28. exit (1);
  29. }
  30. /* Check that val is an int (if you're paranoid or if you need to
  31. * show how this API is used)
  32. */
  33. if (mono_type_get_type (mono_field_get_type (field)) != MONO_TYPE_I4) {
  34. fprintf (stderr, "Field val is not a 32 bit integer\n");
  35. exit (1);
  36. }
  37. /* Note we pass a pointer to the value */
  38. mono_field_get_value (obj, field, &val);
  39. printf ("Value of field is: %d\n", val);
  40. val = 10;
  41. /* Note we pass a pointer to the value here as well */
  42. mono_field_set_value (obj, field, &val);
  43. }
  44. static void
  45. access_reference_field (MonoObject *obj)
  46. {
  47. MonoClass *klass;
  48. MonoDomain *domain;
  49. MonoClassField *str;
  50. MonoString *strval;
  51. char *p;
  52. klass = mono_object_get_class (obj);
  53. domain = mono_object_get_domain (obj);
  54. /* Now we'll see that a reference type is handled slightly differently.
  55. * First, get the MonoClassField representing it.
  56. */
  57. str = mono_class_get_field_from_name (klass, "str");
  58. /* No change here, we always pass a pointer */
  59. mono_field_get_value (obj, str, &strval);
  60. /* get the string in UTF-8 encoding to print it */
  61. p = mono_string_to_utf8 (strval);
  62. printf ("Value of str is: %s\n", p);
  63. /* we need to free the result from mono_string_to_utf8 () */
  64. g_free (p);
  65. /* string are immutable, so we need to create a different string */
  66. strval = mono_string_new (domain, "hello from the embedding API");
  67. /* Here is the slight difference: for reference types we pass
  68. * the pointer directly, instead of a pointer to the value.
  69. */
  70. mono_field_set_value (obj, str, strval);
  71. }
  72. /* Demostrate how to call methods */
  73. static void
  74. call_methods (MonoObject *obj)
  75. {
  76. MonoClass *klass;
  77. MonoDomain *domain;
  78. MonoMethod *method = NULL, *m = NULL, *ctor = NULL, *fail = NULL, *mvalues;
  79. MonoProperty *prop;
  80. MonoObject *result, *exception;
  81. MonoString *str;
  82. char *p;
  83. gpointer iter;
  84. gpointer args [2];
  85. int val;
  86. klass = mono_object_get_class (obj);
  87. domain = mono_object_get_domain (obj);
  88. /* retrieve all the methods we need */
  89. iter = NULL;
  90. while ((m = mono_class_get_methods (klass, &iter))) {
  91. if (strcmp (mono_method_get_name (m), "method") == 0) {
  92. method = m;
  93. } else if (strcmp (mono_method_get_name (m), "Fail") == 0) {
  94. fail = m;
  95. } else if (strcmp (mono_method_get_name (m), "Values") == 0) {
  96. mvalues = m;
  97. } else if (strcmp (mono_method_get_name (m), ".ctor") == 0) {
  98. /* Check it's the ctor that takes two args:
  99. * as you see a contrsuctor is a method like any other.
  100. */
  101. MonoMethodSignature * sig = mono_method_signature (m);
  102. if (mono_signature_get_param_count (sig) == 2) {
  103. ctor = m;
  104. }
  105. }
  106. }
  107. /* Now we'll call method () on obj: since it takes no arguments
  108. * we can pass NULL as the third argument to mono_runtime_invoke ().
  109. * The method will print the updated value.
  110. */
  111. mono_runtime_invoke (method, obj, NULL, NULL);
  112. /* mono_object_new () doesn't call any constructor: this means that
  113. * we'll have to invoke the constructor if needed ourselves. Note:
  114. * invoking a constructor is no different than calling any other method,
  115. * so we'll still call mono_runtime_invoke (). This also means that we
  116. * can invoke a constructor at any time, like now.
  117. * First, setup the array of arguments and their values.
  118. */
  119. /* As usual, we use the address of the data for valuetype arguments */
  120. val = 7;
  121. args [0] = &val;
  122. /* and the pointer for reference types: mono_array_new () returns a MonoArray* */
  123. args [1] = mono_array_new (domain, mono_get_byte_class (), 256);
  124. mono_runtime_invoke (ctor, obj, args, NULL);
  125. /* A property exists only as a metadata entity, so getting or setting the value
  126. * is nothing more than calling mono_runtime_invoke () on the getter or setter method.
  127. */
  128. prop = mono_class_get_property_from_name (klass, "Value");
  129. method = mono_property_get_get_method (prop);
  130. result = mono_runtime_invoke (method, obj, NULL, NULL);
  131. /* mono_runtime_invoke () always boxes the return value if it's a valuetype */
  132. val = *(int*)mono_object_unbox (result);
  133. printf ("Value of val from property is: %d\n", val);
  134. /* we also have an helper method: note that reference types are returned as is */
  135. prop = mono_class_get_property_from_name (klass, "Message");
  136. str = (MonoString*)mono_property_get_value (prop, obj, NULL, NULL);
  137. /* get the string in UTF-8 encoding to print it */
  138. p = mono_string_to_utf8 (str);
  139. printf ("Value of str from property is: %s\n", p);
  140. /* we need to free the result from mono_string_to_utf8 () */
  141. g_free (p);
  142. /* Now we'll show two things:
  143. * 1) static methods are invoked with mono_runtime_invoke () as well,
  144. * we just pass NULL as the second argument.
  145. * 2) we can catch exceptions thrown by the called method.
  146. * Note: fail is declared as static void Fail () in invoke.cs.
  147. * We first set result to NULL: if after the invocation it will have
  148. * a different value, it will be the exception that was thrown from
  149. * the Fail () method. Note that if an exception was thrown, the return
  150. * value (if any) is undefined and can't be used in any way (yes, the above
  151. * invocations don't have this type of error checking to make things simpler).
  152. */
  153. exception = NULL;
  154. mono_runtime_invoke (fail, NULL, NULL, &exception);
  155. if (exception) {
  156. printf ("An exception was thrown in Fail ()\n");
  157. }
  158. /* Now let's see how to handle methods that take by ref arguments:
  159. * Valuetypes continue to be passed as pointers to the data.
  160. * Reference arguments passed by ref (ref or out is the same)
  161. * are handled the same way: a pointer to the pointer is used
  162. * (so that the result can be read back).
  163. * Small note: in this case (a System.Int32 valuetype) we can just
  164. * use &val where val is a C 32 bit integer. In the general case
  165. * unmanaged code doesn't know the size of a valuetype, since the
  166. * runtime may decide to lay it out in what it thinks is a better way
  167. * (unless ExplicitLayout is set). To avoid issues, the best thing is to
  168. * create an object of the valuetype's class and retrieve the pointer
  169. * to the data with the mono_object_unbox () function.
  170. */
  171. val = 100;
  172. str = mono_string_new (domain, "another string");
  173. args [0] = &val;
  174. args [1] = &str;
  175. mono_runtime_invoke (mvalues, obj, args, NULL);
  176. /* get the string in UTF-8 encoding to print it */
  177. p = mono_string_to_utf8 (str);
  178. printf ("Values of str/val from Values () are: %s/%d\n", p, val);
  179. /* we need to free the result from mono_string_to_utf8 () */
  180. g_free (p);
  181. }
  182. static void
  183. more_methods (MonoDomain *domain)
  184. {
  185. MonoClass *klass;
  186. MonoMethodDesc* mdesc;
  187. MonoMethod *method, *vtmethod;
  188. MonoString *str;
  189. MonoObject *obj;
  190. char *p;
  191. int val;
  192. /* Now let's call an instance method on a valuetype. There are two
  193. * different case:
  194. * 1) calling a virtual method defined in a base class, like ToString ():
  195. * we need to pass the value boxed in an object
  196. * 2) calling a normal instance method: in this case
  197. * we pass the address to the valuetype as the second argument
  198. * instead of an object.
  199. * First some initialization.
  200. */
  201. val = 25;
  202. klass = mono_get_int32_class ();
  203. obj = mono_value_box (domain, klass, &val);
  204. /* A different way to search for a method */
  205. mdesc = mono_method_desc_new (":ToString()", FALSE);
  206. vtmethod = mono_method_desc_search_in_class (mdesc, klass);
  207. str = (MonoString*)mono_runtime_invoke (vtmethod, &val, NULL, NULL);
  208. /* get the string in UTF-8 encoding to print it */
  209. p = mono_string_to_utf8 (str);
  210. printf ("25.ToString (): %s\n", p);
  211. /* we need to free the result from mono_string_to_utf8 () */
  212. g_free (p);
  213. /* Now: see how the result is different if we search for the ToString ()
  214. * method in System.Object: mono_runtime_invoke () doesn't do any sort of
  215. * virtual method invocation: it calls the exact method that it was given
  216. * to execute. If a virtual call is needed, mono_object_get_virtual_method ()
  217. * can be called.
  218. */
  219. method = mono_method_desc_search_in_class (mdesc, mono_get_object_class ());
  220. str = (MonoString*)mono_runtime_invoke (method, obj, NULL, NULL);
  221. /* get the string in UTF-8 encoding to print it */
  222. p = mono_string_to_utf8 (str);
  223. printf ("25.ToString (), from System.Object: %s\n", p);
  224. /* we need to free the result from mono_string_to_utf8 () */
  225. g_free (p);
  226. /* Now get the method that overrides ToString () in obj */
  227. vtmethod = mono_object_get_virtual_method (obj, method);
  228. if (mono_class_is_valuetype (mono_method_get_class (vtmethod))) {
  229. printf ("Need to unbox this for call to virtual ToString () for %s\n", mono_class_get_name (klass));
  230. }
  231. mono_method_desc_free (mdesc);
  232. }
  233. static void
  234. create_object (MonoDomain *domain, MonoImage *image)
  235. {
  236. MonoClass *klass;
  237. MonoObject *obj;
  238. klass = mono_class_from_name (image, "Embed", "MyType");
  239. if (!klass) {
  240. fprintf (stderr, "Can't find MyType in assembly %s\n", mono_image_get_filename (image));
  241. exit (1);
  242. }
  243. obj = mono_object_new (domain, klass);
  244. /* mono_object_new () only allocates the storage:
  245. * it doesn't run any constructor. Tell the runtime to run
  246. * the default argumentless constructor.
  247. */
  248. mono_runtime_object_init (obj);
  249. access_valuetype_field (obj);
  250. access_reference_field (obj);
  251. call_methods (obj);
  252. more_methods (domain);
  253. }
  254. static void main_function (MonoDomain *domain, const char *file, int argc, char **argv)
  255. {
  256. MonoAssembly *assembly;
  257. /* Loading an assembly makes the runtime setup everything
  258. * needed to execute it. If we're just interested in the metadata
  259. * we'd use mono_image_load (), instead and we'd get a MonoImage*.
  260. */
  261. assembly = mono_domain_assembly_open (domain, file);
  262. if (!assembly)
  263. exit (2);
  264. /*
  265. * mono_jit_exec() will run the Main() method in the assembly.
  266. * The return value needs to be looked up from
  267. * System.Environment.ExitCode.
  268. */
  269. mono_jit_exec (domain, assembly, argc, argv);
  270. create_object (domain, mono_assembly_get_image (assembly));
  271. }
  272. int
  273. main (int argc, char* argv[]) {
  274. MonoDomain *domain;
  275. const char *file;
  276. int retval;
  277. if (argc < 2){
  278. fprintf (stderr, "Please provide an assembly to load\n");
  279. return 1;
  280. }
  281. file = argv [1];
  282. /*
  283. * mono_jit_init() creates a domain: each assembly is
  284. * loaded and run in a MonoDomain.
  285. */
  286. domain = mono_jit_init (file);
  287. main_function (domain, file, argc - 1, argv + 1);
  288. retval = mono_environment_exitcode_get ();
  289. mono_jit_cleanup (domain);
  290. return retval;
  291. }