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

Michael Foord fuzzyman at voidspace.org.uk
Wed Mar 18 16:45:01 CET 2009


Jonatan Nilsson wrote:
> Hi there Michael Foord.
>
> How do I set the delegate inside the scope?
>

Something like:

var something = delegate(string arg) {
    Console.WriteLine(arg);
};

scope.SetVariable("something", something);

HTH

Michael Foord

>
> 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 :)
>>>   
>>
>>
> _______________________________________________
> Users mailing list
> Users at lists.ironpython.com
> http://lists.ironpython.com/listinfo.cgi/users-ironpython.com


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




More information about the Ironpython-users mailing list