Running IronPython object from C# with dynamic keyword

非 Y 不嫁゛ 提交于 2019-12-23 04:03:06

问题


I have the following IronPython code.

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

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();
}

Can I make this code simpler with dynamic DLR?

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.

ADDED

I attach the source/batch file for the program. Program.cs runme.bat


回答1:


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();


来源:https://stackoverflow.com/questions/3909758/running-ironpython-object-from-c-sharp-with-dynamic-keyword

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!