我正在尝试使用 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)
尝试通过Action
or Func
而不仅仅是原始函数:
我在这里使用了 IronPython(因为现在我的任何机器上都没有安装 mono,但是根据 Python.NET文档我认为应该有效
实际上你的代码几乎没问题,但你需要导入Action
or Func
委托取决于您的需要。
蟒蛇代码:
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# code:
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 的文档使用泛型又发现了这个Python.NET 泛型类型的命名和解析看起来你需要明确指定参数类型
从那里引用:
(反映的)泛型类型定义(如果存在泛型类型
定义与
给定基本名称,并且没有具有该名称的非泛型类型)。这个通用类型
可以使用 [] 语法将定义绑定到封闭泛型类型。尝试去
使用 () 实例化泛型类型 def 会引发 TypeError。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)