Skip to content

Instantly share code, notes, and snippets.

@gedim21
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
mono_set_dirs("./mono/lib",
"./mono/etc");
// load the default Mono configuration file in 'etc/mono/config'
mono_config_parse(NULL);
MonoDomain* monoDomain = mono_jit_init_version("embedding_mono_domain",
"v4.0.30319");
MonoAssembly* monoAssembly = mono_domain_assembly_open(monoDomain,
"MonoGenerics.dll");
MonoImage* monoImage = mono_assembly_get_image(monoAssembly);
MonoClass* testClass = mono_class_from_name(monoImage,
"MonoGenerics",
"TestClass");
MonoObject* testClassInstance = mono_object_new(monoDomain, testClass);
// find GenericMember method
MonoMethod* genericMethod = mono_class_get_method_from_name(testClass,
"GenericMethod",
1);
MonoMethod* helperMethod = mono_class_get_method_from_name(testClass,
"MakeGenericMethod",
2);
MonoReflectionMethod* monoReflectionMethod = mono_method_get_object(monoDomain,
genericMethod,
testClass);
MonoType* monoType = mono_reflection_type_from_name("System.String", monoImage);
MonoReflectionType* monoReflectionType = mono_type_get_object(monoDomain,
monoType);
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
mono_jit_cleanup(monoDomain);
return 0;
}
using System;
using System.Reflection;
namespace MonoGenerics
{
public class TestClass
{
public void GenericMethod<T>(T t)
{
Console.WriteLine(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