Message Boards Message Boards

Use C# generic method in Mathematica .NET/Link?

GROUPS:

Hi,

I'm trying to call an external method in the Mathematica, but I do not know how to do it. Do you have any experience with calling generic methods from Mathematica? Generic methods are a powerful tool, but I do not know how to connect them to Mathematica.

There is the fragment of my code in C# (only for information):

namespace SpaceMyClass
{

public class MyClass 
{
List<object[]> element;
int elementLen = 0;

public void fillElements()
{
… //function for add elements to List 

}

 public T[] column<T>(int x)
        {
            T[] res = new T[elementLen];
            for (int i = 0; i < elementLen; i++)
            {
                res[i] = (T)element[i][x];
            }
            return res;
        }
}
}

I would like to convert this C# code into Mathematica:

SpaceMyClass.MyClass form = new SpaceMyClass.MyClass();
form.fillElements();
string[] st = form.column<string>(0);

I tried this code:

Needs["NETLink`"];
InstallNET[];
LoadNETAssembly[NotebookDirectory[]<>"SpaceMyClass.dll"];  
form=NETNew["SpaceMyClass.MyClass"];
form@fillElements[];

But I do not know how to rewrite last line to Mathematica:

string[] st = myClass.column<string>(0);

Because the code contains <string> and I can not find in Mathematica help or elsewhere how to do it.

I'll be glad for any ideas on how to keep the generics method and use it in Mathematica

POSTED BY: Mirek M
Answer
4 months ago

You may want to try MakeNETObject. Take a look at this similar question with JLink

POSTED BY: Shenghui Yang
Answer
4 months ago

Hi,

Thank you for your feedback. I looked at the link, but the example did not help me.

During searching on the Internet I found another interesting link:

https://stackoverflow.com/questions/232535/how-do-i-use-reflection-to-call-a-generic-method

and this link helped me.

I rewrote the last line to the following C# form:

System.Reflection.MethodInfo method = typeof(SpaceMyClass.MyClass).GetMethod("column");      
System.Reflection.MethodInfo generic = method.MakeGenericMethod(typeof(string)); 
object returnValue=generic.Invoke(myClass, new object[1] { 0 });

Then I rewrote it to the Mathematica

typeMyClass=LoadNETType["SpaceMyClass.MyClass"];
method=GetTypeObject[typeMyClass]@GetMethod["column"];
typeString=LoadNETType["string"];
generic=method@MakeGenericMethod[{GetTypeObject[typeString]}];
st=generic@Invoke[form,{0}]

And this works!

I hope it will help other users who also try the .NET Link

POSTED BY: Mirek M
Answer
4 months ago

Group Abstract Group Abstract