Reputation: 1209
I want to delegate all method call to C# DLL that we have written. I am using pythonnet to load the DLL file and call the methods from the DLL.
This is my python class and it works fine,
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)
But I am not doing anything in python code except making a call to dll methods, so I don't want to write wrapper methods for all the methods in dll.
The above approach allows me to call python methods like, MyProxy().method1(first_arg, arg2, arg3, arg4)
, which in turns passes the first_arg
as the first argument and arg2, arg3, arg4
as an array in the second argument to self.lib.method1(first_arg, args)
.
This behavior is necessary for me because all of my C# methods have signature method1(String first_arg, String[] other_args)
How can I achieve this by only implementing __getattr__
in my python class?
I have tried the below approach, but it throws error "No matching methods found",
class MyProxy:
def __init__(self):
self.lib = MyLibrary()
def __getattr__(self, item):
return getattr(self.lib, item)
Edit: I think, when I wrap a DLL method like this,
def method1(self, first_arg, *args):
self.lib.method1(first_arg, args)
python takes care of converting other arguments except the first one to an array and pass that array to DLL method. It matches the signature of DLL method(method1(String first_arg, String[] other_args)
), since python passes the second argument as an array.
Can we do anything in __getattr__
method to do the array conversion of other arguments except first one and pass on to DLL methods ?
Upvotes: 4
Views: 557
Reputation: 20640
Not tested, but something like this might work:
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
Upvotes: 1