Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning an IronPython method to a C# delegate

I have a C# class that looks a little like:

public class MyClass
{
    private Func<IDataCource, object> processMethod = (ds) =>
                                                          {
                                                            //default method for the class
                                                          }

    public Func<IDataCource, object> ProcessMethod
    {
        get{ return processMethod; }
        set{ processMethod = value; }
    }

    /* Other details elided */
}

And I have an IronPython script that gets run in the application that looks like

from MyApp import myObj #instance of MyClass

def OtherMethod(ds):
    if ds.Data.Length > 0 :
        quot = sum(ds.Data.Real)/sum(ds.Data.Imag)
        return quot
    return 0.0

myObj.ProcessMethod = OtherMethod

But when ProcessMethod gets called (outside of IronPython), after this assignment, the default method is run.

I know the script is run because other parts of the script work.

How should I be doing this?

like image 411
Matt Ellen Avatar asked Oct 18 '10 11:10

Matt Ellen


People also ask

What is the difference between IronPython and Python?

IronPython. Just as Jython is an implementation of Python on the JVM, IronPython is an implementation of Python on the . Net runtime, or CLR (Common Language Runtime). IronPython uses the DLR (Dynamic Language Runtime) of the CLR to allow Python programs to run with the same degree of dynamism that they do in CPython.

What is IronPython used for?

This means that IronPython can be used for client-side scripting in the browser. IronPython is a Python compiler. It compiles Python code to in memory bytecode before execution (which can be saved to disk, making binary only distributions possible).

Is IronPython compatible with Python 3?

IronPython can use . NET and Python libraries, and other . NET languages can use Python code just as easily. IronPython 3 targets Python 3, including the re-organized standard library, Unicode strings, and all of the other new features.


1 Answers

I did some further Googling and found a page about the darker corners of IronPython: http://www.voidspace.org.uk/ironpython/dark-corners.shtml

What I should be doing is this:

from MyApp import myObj #instance of MyClass
import clr
clr.AddReference('System.Core')
from System import Func

def OtherMethod(ds):
    if ds.Data.Length > 0 :
        quot = sum(ds.Data.Real)/sum(ds.Data.Imag)
        return quot
    return 0.0

myObj.ProcessMethod = Func[IDataSource, object](OtherMethod)
like image 181
Matt Ellen Avatar answered Sep 29 '22 02:09

Matt Ellen