3

我必须创建一个 tlb 文件,这样我才能从 .Net 访问 Python COM 服务器。我只想要一个接受字符串并返回字符串的方法(Process)。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'

如何定义一种方法来获取字符串参数并返回一个?

4

1 回答 1

3

这有效

HRESULT Process([in] BSTR str, [out, retval] VARIANT *pResult);
于 2012-07-16T07:00:50.583 回答