c# - 如何在 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 方法吗?
解决方案
未经测试,但这样的事情可能会起作用:
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
推荐阅读
- javascript - document.activeElement 条件不起作用(id 或 ref 在 div 元素内)
- google-cloud-platform - 如何连接到 mqtt.googleapis.com
- excel - VBA 列表框显示带有货币格式的错误符号
- perl - perl-5.14.2 使测试失败
- java - 我可以让轮询器在 start() 命令之后使用 WAIT 开始他的周期吗?
- reactjs - 未处理的拒绝(TypeError):无法在已撤销的代理上执行“获取”
- python - 如何从列表变量中的每组向量中删除单引号?
- mysql - 无法通过套接字'/run/mysqld/mysqld.sock 连接到本地 MySQL 服务器
- ssconvert - SSconvert 将日期转换为 YYYY-MM-DD,而不考虑 xlsx 日期格式
- three.js - 三个Js:不同的颜色到不同的几何面