如何将python回调传递给c#函数调用

我正在尝试使用python中的C#类,在mono / ubuntu上使用python.net。

到目前为止,我设法用一个参数工作做一个简单的函数调用。 我现在要做的是将python回调传递给C#函数调用。

我在下面尝试了以下变化,没有效果。 有人可以展示如何使这项工作?

// 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脚本

 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) 

尝试传递ActionFunc而不仅仅是原始函数:

我在这里使用IronPython(因为现在我没有在我的任何机器上安装单声道,但根据Python.NET 文档,我认为它应该工作实际上你的代码几乎没问题,但你需要导入ActionFunc委托取决于什么你需要。

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 

C#代码:

 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命名和generics类型的解析看起来像你需要明确指定参数类型

从那里引用 :

(reflection)generics类型定义(如果存在具有给定基本名称的generics类型定义,并且没有具有该名称的非generics类型)。 可以使用[]语法将此generics类型定义绑定到封闭的generics类型中。 尝试使用()实例化generics类型def会引发TypeError。

看起来您应该明确定义Delegate:

 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代码(这是一个基于文档的粗略猜测):

 def f(): print "Executing f" # instantiate a delegate f2 = testlib.MC.Callback(f) # use it mc.method2(f2)