0

I am trying to pass a static c# class into python using pythonnet. I am able to use scope.Set("person", pyPerson) similar to sample below. However in my case this is a utility (static) class and I get error that util does not contain testfn in sample below.

using Python.Runtime;

// create a person object
Person person = new Person("John", "Smith");

// acquire the GIL before using the Python interpreter
using (Py.GIL())
{
// create a Python scope
using (PyScope scope = Py.CreateScope())
{
 // convert the Person object to a PyObject
   PyObject pyPerson = person.ToPython();

   // create a Python variable "person"
   scope.Set("person", pyPerson); //<------ this works
   scope.Set("util", Utility); //<------ Utility is a static class whose method I am trying to call 
                               //and this does not  work.

   // the person object may now be used in Python
   string code = "fullName = person.FirstName + ' ' + person.LastName"; //<--- works
   code = "util.testfn();" //testfn is a static class, How do I do this ?
   scope.Exec(code);`enter code here`
  }
 }
gr stack
  • 3
  • 1

1 Answers1

0

If you need to use multiple methods from your Utility class, this post can help:

Python for .NET: How to call a method of a static class using Reflection?

A more convenient way if you just need to call one method is to pass in a delegate. Declare the delegate at class level;

delegate string testfn();

And pass the function pointer to your scope:

scope.Set("testfn", new testfn(Utility.testfn));

In this case, you will be able to call this method directly:

code = @"print(testfn())";

Output: (The testfn() returns "Result of testfn()")

C:\Temp\netcore\console>dotnet run
Result of testfn()
Oguz Ozgul
  • 6,809
  • 1
  • 14
  • 26
  • Ozgul,Thanks for your prompt response. Iron python allows us to do that using DynamicHelpers. I did not find a similar solution using pythonnet. In this case the utility class is in same project and has multiple methods. I thought that reflection was not a straight forward way to do this since it resides in same project. The delegate option is an interesting way to do this. Is there a easier way to do this without using reflection ? – gr stack Apr 26 '20 at 01:41
  • It looks like IronPython has put immense effort in compiling a proxy assembly to make this happen. https://github.com/IronScheme/IronScheme/tree/master/IronScheme/Microsoft.Scripting/Generation. I don't think pythonnet has support for such kind of thing. For now, delegates seems to be a reliable solution but requires extra typing for each static method. – Oguz Ozgul Apr 26 '20 at 08:29
  • Thank you, be safe, and if you Find anything better, please also let me know through here – Oguz Ozgul Apr 26 '20 at 12:29