在Python中使用COM dll?

3 投票
1 回答
2852 浏览
提问于 2025-04-18 14:15

我需要在我的Python项目中使用一个用CSharp制作的COM DLL。

我试着按照这个例子来做:在脚本语言中使用COM对象 -- 第2部分(Python),但是没有成功。

我的Python代码是:

import sys

# for TkInter GUI support
from Tkinter import *
import tkMessageBox
import tkColorChooser

# for COM support
import comtypes.client as cc
import comtypes

# Load the typelibrary registered with the Windows registry
tlb_id = comtypes.GUID("{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}")
cc.GetModule((tlb_id, 1, 0))

当我运行这个Python类时,出现了这个错误:

> Traceback (most recent call last):   File "C:\Program Files
> (x86)\JetBrains\PyCharm 129.696\helpers\pydev\pydevd.py", line 1481,
> in <module>
>     debugger.run(setup['file'], None, None)   File "C:\Program Files (x86)\JetBrains\PyCharm 129.696\helpers\pydev\pydevd.py", line 1124,
> in run
>     pydev_imports.execfile(file, globals, locals) #execute the script   File "C:/aa_python/gtk_project/main.py", line 7, in <module>
>     from com_class_file import ComClass   File "C:/aa_python/gtk_project\com_class_file.py", line 15, in <module>
>     cc.GetModule((tlb_id, 1, 0))   File "C:\Python27\lib\site-packages\comtypes-1.1.0-py2.7.egg\comtypes\client\_generate.py",
> line 101, in GetModule
>     tlib = comtypes.typeinfo.LoadRegTypeLib(comtypes.GUID(tlib[0]), *tlib[1:])   File "C:\Python27\lib\site-packages\comtypes-1.1.0-py2.7.egg\comtypes\typeinfo.py",
> line 473, in LoadRegTypeLib
>     _oleaut32.LoadRegTypeLib(byref(GUID(guid)), wMajorVerNum, wMinorVerNum, lcid, byref(tlib))   File "_ctypes/callproc.c", line
> 945, in GetResult WindowsError: [Error -2147319779] Library not registered

错误行:

cc.GetModule((tlb_id, 1, 0))

在我的CSharp项目中,我的COM DLL里有这些内容:

接口

[InterfaceType(ComInterfaceType.InterfaceIsDual), Guid("YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY")]
public interface ITestCOM
{
    string say_hello();
}

[ClassInterface(ClassInterfaceType.None), Guid("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")]
public class TestCOM : ITestCOM
{
    public string say_hello()
    {
        return "hello world!";
    }
}

这个上面的COM项目在其他应用程序中使用时运行得很好。我的问题只出现在Python中。

顺便说一下:我的COM DLL已经在Windows注册表中注册了。

有人能帮忙吗?

1 个回答

3

在这里,我找到了一条小窍门,帮助我通过 TLB 文件使用我的 COM dll:

通过注册的 TLB 从 Python 访问未注册的 COM 对象

感谢 Márcio Faustino。

撰写回答