简体   繁体   中英

Using scope.set to assign a static class instead of a variable

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`
  }
 }

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM