2

This SO question provides code to create an instance of a python class in C#.

The following code forces to know the python function name in advance. However I need to specify the class name and the function name to be executed by strings.

ScriptEngine engine = Python.CreateEngine();
ScriptSource source = engine.CreateScriptSourceFromFile("Calculator.py");
ScriptScope scope = engine.CreateScope();
source.Execute(scope);

dynamic class_object = scope.GetVariable("Calculator");
dynamic class_instance = class_object();
int result = class_instance.add(4, 5);  // I need to call the function by a string

2 Answers 2

2

Easiest way to do that is to install nuget package called Dynamitey. It was designed specifically to call dynamic methods (and doing other useful things) on dynamic objects. After you install it, just do:

static void Main(string[] args)
{
    ScriptEngine engine = Python.CreateEngine();
    ScriptSource source = engine.CreateScriptSourceFromFile("Calculator.py");
    ScriptScope scope = engine.CreateScope();
    source.Execute(scope);

    dynamic class_object = scope.GetVariable("Calculator");
    dynamic class_instance = class_object();
    int result = Dynamic.InvokeMember(class_instance, "add", 4, 5);
}

If you want to know what it does under the hood - it uses the same code which is used by C# compiler for dynamic invocations. This is a long story but if you want to read about this, you can do it here for example.

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

Comments

0

You're looking for the Invoke and InvokeMember IronPython methods:

ScriptEngine engine = Python.CreateEngine();
ScriptSource source = engine.CreateScriptSourceFromFile("Calculator.py");
ScriptScope scope = engine.CreateScope();
source.Execute(scope);

object class_object = scope.GetVariable("Calculator");
object class_instance = engine.Operations.Invoke(class_object);
object[] args = new object[2];
args[0] = 4;
args[1] = 5;
int result = (int)engine.Operations.InvokeMember(class_instance, "add", args);  // Method called by string
                                                                                //  "args" is optional for methods which don't require arguments.

I also changed the dynamic type to object, since you won't need it anymore for this code sample, but you are free to keep it, should you need to call some fixed-name methods.

Comments

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.