Running IronPython object from C# with dynamic key

2019-05-29 14:29发布

问题:

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