Saturday, 20 October 2018

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

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)



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

No comments:

Post a Comment