tags:

views:

241

answers:

3

Here's the situation...I want to be able to pass a python lambda into C# method where the evaluation of the lambda should happen. when I pass in the lambda, it turns into an instance of a PythonFunction. I am stuck here as I don't know how to execute this PythonFunction. I see a "call" on this class, but I don't know where to get the CodeContext it requires.

Anyone know how to do this?

+2  A: 

There's a similar question here:

http://stackoverflow.com/questions/799987/how-to-pass-a-lambda-expression-to-a-c-constructor-from-an-ironpython-script

The idea was to use a System.Action delegate to accept the python function and then execute that delegate like you would any other. I'm not 100% sure, but I think it will work with an IronPython lamda as long as your System.Action delegate matches.

I hope this works for you.

Scott Anderson
Or System.Func if you need a return type.
Jeff Hardy
A: 

Ok, I figured it out:

var target = myfunction.__code__.Target;
result =  target.DynamicInvoke(new object[] {myfunction, argsForFunction})

where myfunction is a PythonFunction instance.

Mike Gates
Prefer using engine.ObjectOperations instead of relying on implmentation details.
Jeff Hardy
You're right. I gave the answer to you. Thanks!
Mike Gates
+1  A: 

If you don't want to (or can't) use a delegate, the ObjectOperations class is a better bet. It is accessible from engine.ObjectOperations (where engine is your ScriptEngine instance).

if(engine.ObjectOperations.IsCallable(myfunction))
    engine.ObjectOperations.Invoke(myfunction, args);

That said, a strongly-typed delegate (System.Action or System.Func, or one of your own) is a better option. You can use engine.ObjectOperations.ConvertTo to get a delegate if changing the function signature isn't an option.

Jeff Hardy