简体   繁体   English

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

[英]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.我正在尝试使用 pythonnet 将 static c# class 传递给 python I am able to use scope.Set("person", pyPerson) similar to sample below.我可以使用类似于下面示例的 scope.Set("person", pyPerson) 。 However in my case this is a utility (static) class and I get error that util does not contain testfn in sample below.但是,在我的情况下,这是一个实用程序(静态)class,我收到错误,即 util 在下面的示例中不包含 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`
  }
 }

If you need to use multiple methods from your Utility class, this post can help:如果您需要使用实用程序 class 中的多种方法,这篇文章可以提供帮助:

Python for .NET: How to call a method of a static class using Reflection? Python for .NET:如何使用反射调用 static ZA2F2ED4F8EBC2CBB1DZC21A29DC40 的方法

A more convenient way if you just need to call one method is to pass in a delegate.如果您只需要调用一个方法,一种更方便的方法是传入一个委托。 Declare the delegate at class level;在 class 级别声明代表;

delegate string testfn();

And pass the function pointer to your scope:并将 function 指针传递给您的 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()") Output:(testfn()返回“testfn()的结果”)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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