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

Jonatan Nilsson blackman at simnet.is
Wed Mar 18 15:44:40 CET 2009


Hi there Michael Foord.

How do I set the delegate inside the scope?


Sincerely:
Jonatan Nilsson
Iceland

Michael Foord wrote:
> 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 :)
>>   
>
>



More information about the Ironpython-users mailing list