2012-07-16 77 views
3

我必須創建一個tlb文件,以便我可以從.Net訪問Python COM服務器。我只想要一個方法(Process),它接受一個字符串並返回一個字符串。 IDL文件如下:idl的Python COM服務器

import "oaidl.idl"; 
import "ocidl.idl"; 
[ 
    uuid(A66551C8-ADB4-4A1E-BB19-39F356282A7E), 
    dual, 
    oleautomation 
] 
interface IMyInterface : IDispatch { 
    HRESULT Process([in, out] BSTR str); 
} 

[ 
    uuid(BE0CDA23-A2D0-40E5-8D33-61DBE78E0A03) 
] 
library MyTypeLib 
{ 
    importlib("stdole2.tlb"); 

    [uuid(F235B9D8-9C1A-44C3-A59F-3C822EC82A67)] 
      coclass MyObject { 
      [default] interface IMyInterface; 
    }; 
}; 

使用MIDL這成功地生成一個TLB文件 Python程序是如下:

import comtypes 
import comtypes.server.localserver 

from comtypes.client import GetModule 
# generate wrapper code for the type library, this needs 
# to be done only once (but also each time the IDL file changes) 
GetModule("audiclave.tlb") 

from comtypes.gen.MyTypeLib import MyObject 

class AudiclaveImpl(MyObject): 
    # registry entries 
    _reg_threading_ = "Both" 
    _reg_progid_ = "Audiclave.Analysis.1" 
    _reg_novers_progid_ = "Audiclave.Analysis" 
    _reg_desc_ = "Python engine for Audiclave" 
    _reg_clsctx_ = comtypes.CLSCTX_INPROC_SERVER | comtypes.CLSCTX_LOCAL_SERVER 
    _regcls_ = comtypes.server.localserver.REGCLS_MULTIPLEUSE 

    def Process(self, a): 
     return str(a) + "executed" 


if __name__ == "__main__": 
    from comtypes.server.register import UseCommandLine 
    UseCommandLine(AudiclaveImpl) 

我運行與

python audiclaveAnalysis.py /regserver 

現在我打開蟒蛇並執行以下操作:

>>> from comtypes.client import CreateObject 
>>> x = CreateObject("Audiclave.Analysis") 
# Generating comtypes.gen._BE0CDA23_A2D0_40E5_8D33_61DBE78E0A03_0_0_0 
>>> x.Process("test") 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "C:\Python26\lib\site-packages\comtypes\__init__.py", line 596, in call_with_inout 
v = atyp.from_param(v) 
AttributeError: 'str' object has no attribute 'from_param' 

如何定義一個方法來獲取字符串參數並返回一個?

回答

3

這個工作

HRESULT Process([in] BSTR str, [out, retval] VARIANT *pResult); 
+0

謝謝張貼你找到了解決辦法 – ambrus 2012-09-26 23:21:28