Reputation: 2229
I have a non-static C# class with some instance methods, which I need to call from IronPython scripts. Currently I'm doing it this way:
scope.SetVariable("class", instanceOfClass);
in C# code and
class.SomeMethod(args)
in script.
What I want is being able to call this class methods without adding class.
each time in the script. Each script has its own instance of the class, and only one instance is used in one script.
If this class was static, the solution would be from ClassName import *
, but as I know there is no similar construction for non-static classes.
How can this be done? I have some ideas (such as using reflection, or adding class.
to each call in Python source programmatically), but they are overcomplicated and may be even not possible to implement.
UPD:
Problem solved by using such python code (before actual script):
def Method1(arg1): # for simple method
class.Method1(arg1)
def Method2(arg = 123): # for default values
class.Method2(arg)
def Method3(*args): # for params
class.Method3(args)
# so on
Upvotes: 1
Views: 1068
Reputation: 3434
from ClassName import *
is actually from namespace import type
. This statement makes the type avaiable for use via the type name in Python. It makes no difference if the class is static or not. Consider this sample code - Environment being the static class.
import clr
from System import Environment
print Environment.CurrentDirectory
To solve your problem, inject a delegate to the class function into your ScriptScope, rather than the class itself.
Sample class
public class Foo {
public string GetMyString(string input) {
return input;
}
}
Usage
private static void Main(string[] args) {
ScriptEngine engine = Python.CreateEngine();
string script = "x = GetMyString('value')";
Foo foo = new Foo();
ScriptSource scriptSource = engine.CreateScriptSourceFromString(script);
ScriptScope scope = engine.CreateScope();
scope.SetVariable("GetMyString", new Func<string, string>(foo.GetMyString));
scriptSource.Execute(scope);
string output = scope.GetVariable<string>("x");
Console.WriteLine(output);
}
prints
value
Upvotes: 2