Skip to main content
 首页 » 编程设计

c#之从 IronPython 调用带有可变参数的 CLR 方法

2024年02月20日12Leo_wl

我使用 Iron Python 作为附加的“免费”工具来测试将通信包装到某些自定义硬件的 API,以便非开发团队可以通过 Python 来使用硬件。

但是我不知道如何让 .NET void func(params object[] args) 映射到 Python def (*args)。

这里有一些代码来解释。

我有一个类型允许注入(inject)日志回调来格式化和处理消息,它遵循 Console.WriteLine 和 Debug.WriteLine 的签名。

public class Engine 
{ 
    Action<string, object[]> _logger; 
    public void Run() 
    { 
        Log("Hello '{0}'", "world"); 
    } 
    public void SetLog(Action<string, object[]> logger) 
    { 
        _logger = logger; 
    } 
    void Log(string msg, params object[] args) 
    { 
        _logger(msg, args); 
    } 
} 

在我的 IronPython 代码中

import clr 
from System import * 
from System.IO import Path 
clr.AddReferenceToFileAndPath(Path.GetFullPath(r"MyAssembly.dll")) 
from MyNamespace import * 
 
def logger(msg, *args): 
    print( String.Format(msg, args)) 
    print( String.Format(msg, list(args))) 
    print( String.Format(msg, [args])) 
    a=[] 
    for i in args: 
        a.append(i) 
    print( String.Format(msg, a) ) 
 
e = Engine() 
e.SetLog(logger) 
e.Run() 

输出

Hello '('world',)' 
Hello 'IronPython.Runtime.List' 
Hello 'IronPython.Runtime.List' 
Hello 'IronPython.Runtime.List' 

我愿意

Hello 'world' 

请您参考如下方法:

因为 String.Format将你的 iron python 对象(第一个输出案例的元组,最后三个的列表)作为单个对象处理,并且不知道你希望将 python 集合用作 params object[]你得到了意想不到的输出。单个 python 对象/元组在 def logger 时隐式创建被调用。

根据您的实际用例/风格,您可以用不同的方式解决这个问题。

像 Jeff 在他的回答中解释的那样,最 python-y 的方法是在他们的调用站点扩展参数:

def logger(msg, *args): 
    print( String.Format(msg, *args) ) 

如果您调用 logger仅来自 CLR 作为 Action<string, object[]> 的实现你可以有 args是 object[] 类型的单个(非变量)参数喜欢

def logger(msg, args): 
    print( String.Format(msg, args) ) 

如果您想调用logger来自带有可变参数的 python(并且你不介意来回转换)你可以做

def logger(msg, *args): 
    print( String.Format(msg, Array[object](args)) )