Python 如何将所有方法调用委托给 C# DLL

How to delegate all method calls to C# DLL in Python

我想将所有方法调用委托给我们编写的 C# DLL。我正在使用 pythonnet 加载 DLL 文件并从 DLL 调用方法。

这是我的 python class,它工作正常,

import clr
clr.AddReference('MyDll')
from MyDll import MyLibrary


class MyProxy:
    def __init__(self):
        self.lib = MyLibrary()

    def method1(self, first_arg, *args):
        self.lib.method1(first_arg, args)

    def method2(self, first_arg, *args):
        self.lib.method2(first_arg, args)

但我在 python 代码中除了调用 dll 方法外没有做任何事情,所以我不想为 dll 中的所有方法编写包装方法。

上述方法允许我调用 python 方法,例如 MyProxy().method1(first_arg, arg2, arg3, arg4),它依次将 first_arg 作为第一个参数传递,并将 arg2, arg3, arg4 作为数组传递给self.lib.method1(first_arg, args) 的第二个参数。

这种行为对我来说是必要的,因为我所有的 C# 方法都有签名 method1(String first_arg, String[] other_args)

如何通过在我的 python class 中仅实施 __getattr__ 来实现这一点?

我试过下面的方法,但它抛出错误 "No matching methods found",

class MyProxy:
    def __init__(self):
        self.lib = MyLibrary()

    def __getattr__(self, item):
        return getattr(self.lib, item)

编辑: 我想,当我像这样包装 DLL 方法时,

def method1(self, first_arg, *args):
    self.lib.method1(first_arg, args)

python 负责将除第一个参数之外的其他参数转换为数组,并将该数组传递给 DLL 方法。它匹配 DLL 方法的签名(method1(String first_arg, String[] other_args)),因为 python 将第二个参数作为数组传递。

我们可以在 __getattr__ 方法中做任何事情来对除第一个参数之外的其他参数进行数组转换并传递给 DLL 方法吗?

未测试,但类似这样的方法可能有效:

class MyProxy:
    def __init__(self):
        self.lib = MyLibrary()

    def __getattr__(self, item):
        lib_method = getattr(self.lib, item)
        def _wrapper(first_arg, *args):
            return lib_method(first_arg, args)
        return _wrapper