2

I am planning to use IronPython along with C# for following use case.

I want to expose some functions which can invoked via python script.

Such script will be invoked by C# application.

For example there could be function prepared in C# ClearUserInput() that clears some data on WPF. Then I could expose more functions via some interface.

public interface IScriptContract
{
   void ClearMainWindow();
   void LoadProject(string projectName);
}

python script:

print "clearing window"
ClearMainWindow() --how to cooperating with C# code?
print "load proj"
ClearMainWindow("project.proj") --how to cooperating with C# code?

I want user can write some script that can invoke my .net function.

Is it possible to do that?

1

1 Answer 1

2

The standard way to do this is to create a 'host object' that is passed into the scripts that provides access to the host application (if you're familiar with web progamming, that's what the window instance is).

In IronPython you can use SetVariable on the ScriptScope object that is executing your code:

var contract = new ScriptContract();

var engine = Python.CreateEngine();
var mainScope = engine.CreateScope();

var scriptSource = engine.CreateScriptSourceFromFile("test.py", Encoding.Default, SourceCodeKind.File)

mainScope.SetVariable("host", contract);

scriptSource.Execute(scope);

From python it's then always available:

host.ClearMainWindow()
Sign up to request clarification or add additional context in comments.

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.