从C#与动态关键字运行IronPython的对象 [英] Running IronPython object from C# with dynamic keyword
本文介绍了从C#与动态关键字运行IronPython的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下IronPython的代码
I have the following IronPython code.
class Hello:
def __init__(self):
pass
def add(self, x, y):
return (x+y)
我可以做下面的C#代码来使用IronPython的代码。
I could make the following C# code to use the IronPython code.
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?
Can I make this code simpler with dynamic DLR?
借助 IronPython的行动中本书有AT<一下简单的解释; 15.4 0.4动态对象交互>的未来,但我无法找到一些例子。
The IronPython In Action book has the simple explanation about it at <15.4.4 The future of interacting with dynamic objects>, but I couldn't find some examples.
我附上了程序的源/批处理文件。
Program.cs的
的 runme.bat
I attach the source/batch file for the program. Program.cs runme.bat
推荐答案
是的,动态的可以使你的代码simplier
Yes, dynamic can make your code simplier
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#与动态关键字运行IronPython的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文