Skip to content Skip to sidebar Skip to footer

How To Pass Python Callback To C# Function Call

I am trying to use C# classes from python, using python.net on mono / ubuntu. So far I managed to do a simple function call with one argument work. What I am now trying to do is pa

Solution 1:

Try to pass Action or Func instead of just raw function:

I used IronPython here (because right now I don't have mono installed on any of my machines but according of Python.NET documentation I think it should work Actually your code is almost ok but you need to import Action or Func delegate depends on what you need.

python code:

import clr
from types import *
from System import Action
clr.AddReferenceToFileAndPath(r"YourPath\TestLib.dll")
import TestLib
print("Hello")
mc = TestLib.MC()
print(mc.method1(10))

deff(fakeparam):
    print"exec f" 

mc.method2(Action[int](f))

This is a console output:

Hello
Executing method1
42.0
Executing method2
exec f
Done executing method2

C# code:

using System;


namespaceTestLib
{
    publicclassMC
    {
        publicdoublemethod1(int n)
        {
            Console.WriteLine("Executing method1");
            return42.0;
            /* .. */
        }

        publicdoublemethod2(Delegate f)
        {
            Console.WriteLine("Executing method2");
            object[] paramToPass = newobject[1];
            paramToPass[0] = newint();
            f.DynamicInvoke(paramToPass);
            Console.WriteLine("Done executing method2");
            return24.0;

        }
    }
}

I read docs for Python.net Using Generics again and also found this Python.NET Naming and resolution of generic types look like you need to specify parameter type explicitly

quote from there:

a (reflected) generic type definition (if there exists a generic type definition with the given base name, and no non-generic type with that name). This generic type definition can be bound into a closed generic type using the [] syntax. Trying to instantiate a generic type def using () raises a TypeError.

Solution 2:

It looks like you should define your Delegate explicitly:

classMC {
    // Define a delegate typepublicdelegatevoidCallback();

    publicdoublemethod2(Callback f) {
        Console.WriteLine("Executing method2" );
        /* ... do f() at some point ... *//* also tried f.DynamicInvoke() */
        Console.WriteLine("Done executing method2" );
    }
}

Then from the Python code (this is a rough guess based from the docs):

deff():
    print"Executing f"# instantiate a delegate
f2 = testlib.MC.Callback(f)

# use it
mc.method2(f2)

Post a Comment for "How To Pass Python Callback To C# Function Call"