[IronPython] How do I register functions that Python can run from C#?

Michael Foord fuzzyman at voidspace.org.uk
Wed Mar 18 15:27:21 CET 2009


Create a delegate and set it in the scope prior to executing.

Michael

BlackMan890 wrote:
> Hi there.
>
> I was wondering how one would achieve registering a C# function that python
> code would be able to call, something like this:
>
> --- test.py ---------------
>
> def return_crap():
> 	# do something
> 	crap = GetDataFromCSharp()
> 	# do some more
> 	return crap
>
> --------------------------
>
> This is my current C# code:
>
> --- program.cs -----------
>
> static void Main(string[] args)
> {
> 	ScriptEngine engine = Python.CreateEngine();
> 	CompiledCode compile = engine.CreateScriptSourceFromFile("test.py", new
> UTF8Encoding(), SourceCodeKind.Statements).Compile();
> 	ScriptScope scope = engine.CreateScope();
> 	ObjectOperations operations = engine.Operations;
>
> 	try
> 	{
> 		compile.Execute(scope);
> 	}
> 	catch (Exception ex)
> 	{
> 		ExceptionOperations eo = engine.GetService<ExceptionOperations>(); 
> 		Console.WriteLine(eo.FormatException(ex));
> 	}
>
> 	GetData = scope.GetVariable<Func>("return_crap");
>
> 	object data = GetData();
> }
>
> public static object GetDataFromCSharp()
> {
> 	return "test";
> }
>
> --------------------------
>
> Of course an error will occur because GetDataFromCSharp has not yet been
> defined. I was wondering how one would go to register the function :)
>   


-- 
http://www.ironpythoninaction.com/




More information about the Ironpython-users mailing list