Embedded Mono: Invoking a C# generic method (Part 1)

(Edit 8/7/2015: Part 2 of this tutorial can be found here, showing an alternative solution without using C# helper methods)

On a previous post we saw how to embed the Mono runtime in a C++ application, load some C# classes and invoke methods on them. However, when you want to invoke generic methods, things become slightly more complicated.

Let’s say we want to invoke the GenericMethod<T>(T t) from the following class:

We will initialize Mono, load our assembly, and create an instance of the TestClass class:

At this point, we just just need to lookup the GenericMethod method and mono_runtime_invoke it. If we took the usual route and tried this:

we would see that the “name” variable would contain:

It may seem this is what we need, but it isn’t. If we tried to mono_runtime_invoke this method our application would crash. What we need is a specialized method for the type that we need to pass to the GenericMethod. For example, for a String parameter we need a method of signature:

In order to do this, we will facilitate the MethodInfo.MakeGenericMethod method from the System.Reflection namespace. Let’s add the following helper method to our TestClass:

Now on the C++ side we need to lookup this method and invoke it with a MethodInfo for the GenericMethod and a Type for System.String. Its return value will be the specialized GenericMethod method:

If we try the mono_method_full_name on the specializedMethod, we will get:

Now finally, we can invoke the GenericMethod using a String as an argument:

Final notes

  • For methods that take more than one template parameter, we can modify MakeGenericMethod to accept an array to Types. For the sake of simplicity this isn’t portrayed here, but it’s fairly easy to implement.
  • It is also possible to implement the MakeGenericMethod method using entirely the mono API, without using any C# code. But that would take a lot of boilerplate code. It’s a lot easier to include it as C# code in a utility class.
  • Full source code can be found here.

One Reply to “Embedded Mono: Invoking a C# generic method (Part 1)”

  1. Someone could find interesting a tentative to automate this through C++ Class Wrapper for Embedded Mono. https://github.com/brunolauze/MonoNative I did find the look of the final C++ code sleek like .NET CLR C++ lib:

    using namespace mscorlib::System;
    using namespace mscorlib::System::Collections::Generic;

    var *list = new List();
    int count = list->Count;

Leave a Reply

Your email address will not be published. Required fields are marked *