使用 scope.set 分配静态 class 而不是变量

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

我正在尝试使用 pythonnet 将静态 c# class 传递到 python。我可以使用类似于下面示例的 scope.Set("person", pyPerson)。但是,在我的例子中,这是一个实用程序(静态)class,我收到错误消息,即下面的示例中实用程序不包含 testfn。

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

如果您需要使用实用程序 class 中的多种方法,此 post 可以提供帮助:

如果您只需要调用一个方法,一种更方便的方法是传入一个委托。在 class 级别声明委托;

delegate string testfn();

并将函数指针传递给您的范围:

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

在这种情况下,您将可以直接调用此方法:

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

输出:(testfn()returns"Result of testfn()")

C:\Temp\netcore\console>dotnet run
Result of testfn()