开发者

Running IronPython object from C# with dynamic keyword

开发者 https://www.devze.com 2023-01-19 08:41 出处:网络
I have the following IronPython code. class Hello: def __init__(self): pass def add(self, x, y): return (x+y)

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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号