使用ironpython从c#中的python类中的方法读取值

时间:2017-12-24 12:41:51

标签: c# ironpython

我想在c#

中读取此python类中的area方法

有人知道我接下来要做什么来实现这个目标:

Python类: class Shape(object):

def __init__(self,x, y):

     self.x = x
     self.y = y

def area(self):
    return self.x * self.y

C#代码:

        ScriptEngine engine1 = Python.CreateEngine();
        ScriptSource source1 = engine1.CreateScriptSourceFromFile("C:\\C#Projects\\ExcelAddIn\\ExcelAddIn\\Shape.py");
        ScriptScope scope1 = engine1.CreateScope();
        source1.Execute(scope1);

        dynamic class_object1 = scope1.GetVariable("Shape");
        dynamic class_instance1 = class_object1();

1 个答案:

答案 0 :(得分:0)

您必须使用CreateInstance方法(此处提供:https://github.com/jdhardy/ironpython/blob/master/Runtime/Microsoft.Scripting/Hosting/ObjectOperations.cs)。

ScriptEngine engine1 = Python.CreateEngine();
ScriptSource source1 = engine1.CreateScriptSourceFromFile("C:\\C#Projects\\ExcelAddIn\\ExcelAddIn\\Shape.py");
ScriptScope scope1 = engine1.CreateScope();
source1.Execute(scope1);

var class_object1 = scope1.GetVariable("Shape");
var class_instance1 = engine1.Operations.CreateInstance(class_object1, 1, 1); // This should create a shape with x = 1 and y = 1