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
Neuron
  • 5,141
  • 5
  • 38
  • 59
Santi Peñate-Vera
  • 1,053
  • 4
  • 33
  • 68

2 Answers2

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.

Evk
  • 98,527
  • 8
  • 141
  • 191
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.

gog
  • 1,220
  • 11
  • 30