我必须创建一个tlb文件,以便可以从.Net访问Python COM服务器.我只想要一个采用字符串并返回字符串的方法(进程). idl文件如下:
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
现在,我打开python并执行以下操作:
>>> 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'
如何定义一个采用字符串参数并返回一个参数的方法?
解决方法:
这工作
HRESULT Process([in] BSTR str, [out, retval] VARIANT *pResult);