[pypy-dev] mapping C# Delegates to Python

amit regmi.amit at gmail.com
Tue Dec 4 16:19:59 CET 2007


/* C# delegate */

using System;
delegate void Deleg(int x);

class testclass
{
    public static void Method1(int i) {
        Console.WriteLine("testClass.Method1 : "+ i);
    }
    public static void Method2(int i) {
        Console.WriteLine(".Method2 : "+ i*2);
    }
}

class Test {
    static void Main(string[] args) {

        Deleg DL1 = new Deleg(testclass.Method1);
        DL1(-55);

        Deleg DL2 = new Deleg(testclass.Method2);
        DL2(-22);

        Deleg DL3 = DL2 + DL1;
        DL3(-3333);
    }
}

/*
 * Now in Python what I might want to do is
 *
 * import System.Delegate
 *
 * class Deleg(Delegate):
 *      __init__(self, ...):
 *          pass
 *
 * t1 = testclass()
 * DL1 = Deleg(t1.Method1)
 * DL1(-55)         # calls Method1
 *
 * DL2 = Deleg(t1.Method2)
 * DL3 = DL2 + DL1
 *
 * DL2(54)          # calls Method2
 * DL3(32)          # calls Method2 then Method1
 */


I tried :
    import clr
    deleg = clr.load_cli_class('System','Delegate')
    dd = deleg()

and landed up with
    AttributeError: 'NoneType' object has no attribute 'Invoke'

This looks like a rocket science to me but I really have to come up with 
this implementation to prevent myself from the pain of getting a "C"  :(
which now appears almost certain  :((

Need guidance.

-AmitReg




More information about the Pypy-dev mailing list