簡體   English   中英

使用IronPython中的可變參數調用CLR方法

[英]calling CLR method with variable arguments from IronPython

我正在使用Iron Python作為一個額外的“免費”工具來測試一個API,它將comms包裝到一些自定義硬件中,因此非開發團隊可以通過python使用硬件。

但是我無法弄清楚如何將.NET void func(params object[] args)映射到Python def (*args)

這里有一些代碼可以解釋。

我有一個允許注入日志回調格式和處理消息的類型遵循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處理你的鐵python對象(你的第一個輸出案例的元組,最后三個列表)作為單個對象,並且不知道你希望python集合被用作params object[]你得到意外輸出。 調用def logger時會隱式創建單個python對象/元組。

根據您的實際用例/風格,您可以通過不同方式解決此問題。

傑夫在他的回答中解釋說,最蟒蛇的方式是在他們的呼叫網站上擴展爭論:

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

如果僅從CLR調用logger作為Action<string, object[]>你可以讓args成為object[]類型的單個(非變量)參數

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

如果你想用python調用帶有可變參數的logger (並且你不介意來回轉換)你可以做

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

除非我誤解你的問題,否則這應該有效:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM