test-invoke.c 11 KB

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