2

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?

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

There's a similar question here:

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.

1 Comment

Or System.Func if you need a return type.
0

Ok, I figured it out:

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

where myfunction is a PythonFunction instance.

1 Comment

Prefer using engine.ObjectOperations instead of relying on implmentation details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.