tags:

views:

50

answers:

1

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

+2  A: 

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();
desco
@desco : I ran the code to get the following error. Unhandled Exception: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: `IronPython.Runtime.Types.OldInstance' does not contain a definition for `add'at (wrapper dynamic-method) object.CallSite.Target (System.Runtime.CompilerServices.Closure,System.Runtime.CompilerServices.CallSite,object,int,int) <0x0006c>at System.Dynamic.UpdateDelegates.UpdateAndExecute3<object, int, int, object> (System.Runtime.CompilerServices.CallSite,object,int,int) <0x00304>at BasicEmbedding.Program.Main () <0x001b9>
prosseek
@desco : I use mono 2.6 that supports .NET 4.0.
prosseek
that's strange, this code works on Windows.
desco
just interesting, in your python sources, replace 'class Hello:' to 'class Hello(object):'
desco
@desco : Hello(object) doesn't work. I copied the py.exe to Windows, and I got the same error. It might be that Mono 2.6 might not support DRL fully.
prosseek
@desco : I tried to compile/run the source on Windows 7, but I got the same error. Could you check that for me? I added the source and batch file to the original post.
prosseek
yes, I've checked, everything runs like charm, Win XP, Iron Python 2.6.1 for .NET 4.0
desco