How to pass python callback to C # function call

I am trying to use C # classes from python using python.net for mono / ubuntu.

So far, I have managed to make a simple function call using a single argument. Now I'm trying to pass a python callback to a C # function call.

I tried the following options below, no one worked. Can anyone show how to do this?

// C# - testlib.cs
class MC {
    public double method1(int n) {
        Console.WriteLine("Executing method1" );
        /* .. */
    }

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

Python script

import testlib, System
mc = testlib.MC()
mc.method1(10) # that works

def f():
    print "Executing f"

mc.method2(f)  
# does not know of method2 with that signature, fair enough...

# is this the right way to turn it into a callback?
f2 = System.AssemblyLoad(f) 
# no error message, but f does not seem to be invoked
mc.method2(f2)              
+3
source share
2 answers

Try passing Actionor Funcinstead of a simple function:

IronPython ( , Python.NET documentation , , Action Func, , .

python:

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))

def f(fakeparam):
    print "exec f" 

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

:

Hello
Executing method1
42.0
Executing method2
exec f
Done executing method2

#:

using System;


namespace TestLib
{
    public class MC
    {
        public double method1(int n)
        {
            Console.WriteLine("Executing method1");
            return 42.0;
            /* .. */
        }

        public double method2(Delegate f)
        {
            Console.WriteLine("Executing method2");
            object[] paramToPass = new object[1];
            paramToPass[0] = new int();
            f.DynamicInvoke(paramToPass);
            Console.WriteLine("Done executing method2");
            return 24.0;

        }
    }
}

Python.net Generics, Python.NET ,

:

a () (      , ).      [].      generic def, (), TypeError.

+3

, :

class MC {
    // Define a delegate type
    public delegate void Callback();

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

Python ( , docs):

def f():
    print "Executing f"

# instantiate a delegate
f2 = testlib.MC.Callback(f)

# use it
mc.method2(f2)
0

Source: https://habr.com/ru/post/1681337/


All Articles