首页 > 解决方案 > 如何在 Python 中将所有方法调用委托给 C# DLL

问题描述

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

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

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)

但是除了调用 dll 方法之外,我没有在 python 代码中做任何事情,所以我不想为 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)

我怎样才能通过仅__getattr__在我的 python 类中实现来实现这一点?

我尝试了以下方法,但它抛出错误“未找到匹配方法”,

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 方法吗?

标签: c#pythonpython-2.7python.net

解决方案


未经测试,但这样的事情可能会起作用:

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

推荐阅读