Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

Created April 20, 2015 23:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gedim21/c50e46173e9e55083ed4 to your computer and use it in GitHub Desktop.
Save gedim21/c50e46173e9e55083ed4 to your computer and use it in GitHub Desktop.
Embedded Mono: Invoking a C# generic method
#include <mono/jit/jit.h>
#include <mono/metadata/mono-config.h>
#include <mono/metadata/assembly.h>
#include <mono/metadata/debug-helpers.h>
#include <string>
int main()
// point to the relevant directories of the Mono installation
// load the default Mono configuration file in 'etc/mono/config'
MonoDomain* monoDomain = mono_jit_init_version("embedding_mono_domain",
MonoAssembly* monoAssembly = mono_domain_assembly_open(monoDomain,
MonoImage* monoImage = mono_assembly_get_image(monoAssembly);
MonoClass* testClass = mono_class_from_name(monoImage,
MonoObject* testClassInstance = mono_object_new(monoDomain, testClass);
// find GenericMember method
MonoMethod* genericMethod = mono_class_get_method_from_name(testClass,
MonoMethod* helperMethod = mono_class_get_method_from_name(testClass,
MonoReflectionMethod* monoReflectionMethod = mono_method_get_object(monoDomain,
MonoType* monoType = mono_reflection_type_from_name("System.String", monoImage);
MonoReflectionType* monoReflectionType = mono_type_get_object(monoDomain,
void* helperArgs[2];
helperArgs[0] = monoReflectionMethod;
helperArgs[1] = monoReflectionType;
MonoObject* exception = NULL;
MonoObject* boxedResult = mono_runtime_invoke(helperMethod, NULL, helperArgs, NULL);
MonoMethod* specializedMethod = *(MonoMethod**)mono_object_unbox(boxedResult);
void* args[1];
args[0] = mono_string_new(monoDomain, "Finally!");
exception = NULL;
mono_runtime_invoke(specializedMethod, testClassInstance, args, &exception);
// shutdown mono
return 0;
using System;
using System.Reflection;
namespace MonoGenerics
public class TestClass
public void GenericMethod<T>(T t)
public static IntPtr MakeGenericMethod(MethodInfo method, Type type)
return method.MakeGenericMethod(type).MethodHandle.Value;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment