我想将所有方法调用委托给我们编写的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 method(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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句