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?

komizo
  • 1,052
  • 14
  • 21
  • See here - http://stackoverflow.com/questions/7367976/calling-a-c-sharp-library-from-python – Evk Sep 14 '15 at 21:30

1 Answers1

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()
Jeff Hardy
  • 7,632
  • 24
  • 24