如何从C#调用IronPython 2方法

时间:2022-06-14 14:36:32

I can get an IronPython 2 class back to my C#. What is the new IronPython 2 way of calling a member on that class?

我可以将IronPython 2课程带回我的C#。什么是新的IronPython 2方式调用该类的成员?

object ironPythonClass = scope.GetVariable("Hamish");
object[] args = new object[0];
object pythonObject = engine.Operations.Call(ironPythonClass, args);

var member = "Home";
// old way IronPython 1
// var methodResult = Ops.Invoke(this.pythonObject, SymbolTable.StringToId(member), args);

I thought all I'd have to do was

我以为我所要做的就是

var methodResult = PythonOps.Invoke(codeContext, pythonObject, SymbolTable.StringToId(member), args);

but creating a dummy CodeContext doesn't seem to be right. I feel as though I should be able to derive one from my

但是创建一个虚拟的CodeContext似乎并不正确。我觉得我应该能够从我的中获得一个

code.Execute();

that runs the Python file creating the class, plus the scope that arises out of that execution.

运行创建类的Python文件,以及执行中产生的范围。

1 个解决方案

#1


3  

Found a way to do it:

找到了一种方法:

var ops = engine.Operations;
var x = ops.GetMember(pythonObject, member);
var h = ops.Call(x, new object[0]);

Looks like the Operations produces an OperationsObject which has useful members.

看起来Operations会生成一个具有有用成员的OperationsObject。

Looking at the DLR code (Microsoft.Scripting.Hosting) however I see that Call is deprecated:

查看DLR代码(Microsoft.Scripting.Hosting)但是我看到Call已被弃用:

[Obsolete("Use Invoke instead")]
public object Call(object obj, params object[] parameters) {
    return _ops.Invoke(obj, parameters);
}

My version of scripting 0.9.20209, doesn't yet have the Invoke however.

我的脚本0.9.20209的版本,但还没有Invoke。

After updating to the newer IronPython 2.6Beta and its scripting dlls I find I can write:

更新到更新的IronPython 2.6Beta及其脚本dll后,我发现我可以写:

var h = ops.InvokeMember(pythonObject, member, new object[0]);

#1


3  

Found a way to do it:

找到了一种方法:

var ops = engine.Operations;
var x = ops.GetMember(pythonObject, member);
var h = ops.Call(x, new object[0]);

Looks like the Operations produces an OperationsObject which has useful members.

看起来Operations会生成一个具有有用成员的OperationsObject。

Looking at the DLR code (Microsoft.Scripting.Hosting) however I see that Call is deprecated:

查看DLR代码(Microsoft.Scripting.Hosting)但是我看到Call已被弃用:

[Obsolete("Use Invoke instead")]
public object Call(object obj, params object[] parameters) {
    return _ops.Invoke(obj, parameters);
}

My version of scripting 0.9.20209, doesn't yet have the Invoke however.

我的脚本0.9.20209的版本,但还没有Invoke。

After updating to the newer IronPython 2.6Beta and its scripting dlls I find I can write:

更新到更新的IronPython 2.6Beta及其脚本dll后,我发现我可以写:

var h = ops.InvokeMember(pythonObject, member, new object[0]);