test-invoke.c 11 KB

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