Consuming Python COM Server from .NET

前端 未结 2 1549
无人及你
无人及你 2020-12-08 18:08

I wanted to implement python com server using win32com extensions. Then consume the server from within the .NET. I used the following example to implement the com server and

相关标签:
2条回答
  • 2020-12-08 18:15

    A COM server is just a piece of software (a DLL or an executable) that will accept remote procedure calls (RPC) through a defined protocol. Part of the protocol says that the server must have a unique ID, stored in the Windows' registry. In our case, this means that you have "registered" a server that is not existing. Thus the error (component not found).

    So, it should be something like this (as usual, this is untested code!):

    import pythoncom
    
    class HelloWorld:
        _reg_clsctx_ = pythoncom.CLSCTX_LOCAL_SERVER
        _reg_clsid_ = "{B83DD222-7750-413D-A9AD-01B37021B24B}"
        _reg_desc_ = "Python Test COM Server"
        _reg_progid_ = "Python.TestServer"
        _public_methods_ = ['Hello']
        _public_attrs_ = ['softspace', 'noCalls']
        _readonly_attrs_ = ['noCalls']
    
        def __init__(self):
            self.softspace = 1
            self.noCalls = 0
    
        def Hello(self, who):
            self.noCalls = self.noCalls + 1
            # insert "softspace" number of spaces
            return "Hello" + " " * self.softspace + str(who)
    
    if __name__ == '__main__':
        if '--register' in sys.argv[1:]  or '--unregister' in sys.argv[1:]:
            import win32com.server.register
            win32com.server.register.UseCommandLine(HelloWorld)
        else:
            # start the server.
            from win32com.server import localserver
            localserver.serve('B83DD222-7750-413D-A9AD-01B37021B24B')
    

    Then you should run from the command line (assuming the script is called HelloWorldCOM.py):

    HelloWorldCOM.py --register
    HelloWorldCOM.py

    Class HelloWorld is the actual implementation of the server. It expose one method (Hello) and a couple of attributes, one of the two is read-only. With the first command, you register the server; with the second one, you run it and then it becomes available to usage from other applications.

    0 讨论(0)
  • 2020-12-08 18:22

    You need run Process Monitor on your C# Executable to track down the file that is not found.

    0 讨论(0)
提交回复
热议问题