2009-07-05 101 views
2

我實現了一個python com服務器,並使用py2exe工具生成可執行文件和dll。 然後我用regsvr32.exe來註冊dll.I得到一個消息,註冊成功。然後我嘗試在.NET中添加對該dll的引用。我瀏覽到DLL的位置並選擇它,但我得到一個錯誤消息框,說:無法添加對dll的引用,請確保該文件是可訪問的,它是一個有效的程序集或COM組件。下面添加服務器和安裝腳本的代碼。 我想提一下,我可以運行服務器作爲python腳本,並使用後期綁定從.net使用它。 有什麼我失蹤或做錯了?我將不勝感激任何幫助。使用.NET註冊com對象dll

感謝, 薩拉

hello.py

import pythoncom 

import sys 

class HelloWorld: 

    #pythoncom.frozen = 1 
    if hasattr(sys, 'importers'): 
     _reg_class_spec_ = "__main__.HelloWorld" 
    _reg_clsctx_ = pythoncom.CLSCTX_LOCAL_SERVER 
    _reg_clsid_ = pythoncom.CreateGuid() 
    _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 
     print "Hello" + " " * self.softspace + str(who) 
     return "Hello" + " " * self.softspace + str(who) 


if __name__=='__main__': 
    import sys 
    if hasattr(sys, 'importers'): 

     # running as packed executable. 

     if '--register' in sys.argv[1:] or '--unregister' in sys.argv[1:]: 

      # --register and --unregister work as usual 
      import win32com.server.register 
      win32com.server.register.UseCommandLine(HelloWorld) 
     else: 

      # start the server. 
      from win32com.server import localserver 
      localserver.main() 
    else: 

     import win32com.server.register 
     win32com.server.register.UseCommandLine(HelloWorld) 

setup.py

from distutils.core import setup 
import py2exe 

setup(com_server = ["hello"]) 

回答

2

我會回答我的問題,以幫助任何人可能有類似的問題。我希望這會有所幫助。 我無法在COM選項卡上找到我的服務器,因爲.NET(& Visual-Studio)需要帶有TLB的COM服務器。但是Python的COM服務器沒有TLB。 所以要通過(C#和Late binding)從.NET使用服務器。下面的代碼演示如何使這個:

// C#代碼

using System; 

using System.Collections.Generic; 

using System.Linq; 

using System.Text; 

using System.Reflection; 

namespace ConsoleApplication2 

{ 

    class Program 

    { 
     static void Main(string[] args) 

     { 

       Type pythonServer; 
       object pythonObject; 
       pythonServer = Type.GetTypeFromProgID("PythonDemos.Utilities"); 
       pythonObject = Activator.CreateInstance(pythonServer); 

     } 
    } 
} ` 
0

如果你想使用註冊的COM 對象,你需要在找到它Add Reference對話框中的Com選項卡。你不會導航到dll。

+0

謝謝回答,我這樣做,在第一,但沒有找到我在COM選項卡上的服務器,所以我想我會瀏覽到它。 – Sarah 2009-07-05 13:04:35

2

行:

_reg_clsid_ = pythoncom.CreateGuid() 

創建一個新的GUID每次該文件被調用。您可以創建在命令行上一個GUID:

C:\>python -c "import pythoncom; print pythoncom.CreateGuid()" 
{C86B66C2-408E-46EA-845E-71626F94D965} 

,然後更改行:

_reg_clsid_ = "{C86B66C2-408E-46EA-845E-71626F94D965}" 

進行此更改後,我能運行代碼,並與下面的VBScript測試:

Set obj = CreateObject("Python.TestServer") 
MsgBox obj.Hello("foo") 

我沒有MSVC方便看看這是否修復了「添加引用」問題。

+0

感謝您的回答,我遵循您的指南,我註冊了服務器沒有問題。但我仍然無法在COM選項卡上找到我的服務器。 – Sarah 2009-07-05 22:59:07