gpt4 book ai didi

c# - 使用动态关键字从 C# 运行 IronPython 对象

转载 作者:太空宇宙 更新时间:2023-11-03 20:38:51 24 4
gpt4 key购买 nike

我有以下 IronPython 代码。

class Hello:
def __init__(self):
pass
def add(self, x, y):
return (x+y)

我可以编写以下 C# 代码来使用 IronPython 代码。

static void Main()
{

string source = GetSourceCode("ipyth.py");
Engine engine = new Engine(source);
ObjectOperations ops = engine._engine.Operations;

bool result = engine.Execute();
if (!result)
{
Console.WriteLine("Executing Python code failed!");
}
else
{
object klass = engine._scope.GetVariable("Hello");
object instance = ops.Invoke(klass);
object method = ops.GetMember(instance, "add");
int res = (int) ops.Invoke(method, 10, 20);
Console.WriteLine(res);
}

Console.WriteLine("Press any key to exit.");
Console.ReadLine();
}

我可以使用动态 DLR 简化此代码吗?

IronPython In Action <15.4.4 The future of interacting with dynamic objects> 书对此有简单的解释,但我找不到一些例子。

已添加

我附上程序的源文件/批处理文件。 Program.cs runme.bat

最佳答案

是的,动态可以让你的代码更简单

        var source =
@"
class Hello:
def __init__(self):
pass
def add(self, x, y):
return (x+y)

";

var engine = Python.CreateEngine();
var scope = engine.CreateScope();
var ops = engine.Operations;

engine.Execute(source, scope);
var pythonType = scope.GetVariable("Hello");
dynamic instance = ops.CreateInstance(pythonType);
var value = instance.add(10, 20);
Console.WriteLine(value);

Console.WriteLine("Press any key to exit.");
Console.ReadLine();

关于c# - 使用动态关键字从 C# 运行 IronPython 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3909758/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com