You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从Python访问C# COM互操作遇IComInteropClass属性错误的求助

解决comtypes加载C# COM组件时的AttributeError问题

你完全找对了方向!comtypes依赖显式的COM接口定义来生成对应的Python包装类,你的C#代码里只写了实现类ComInteropClass,但没有公开它实现的IComInteropClass接口(即使你在ComDefaultInterface里指定了这个接口,也需要显式定义它并标记为COM可见)。

修正后的完整C#代码

下面是添加了显式接口定义的完整代码,注意接口也要加上[ComVisible(true)]和唯一的[Guid]:

using System;
using System.IO;
using System.Runtime.InteropServices;

namespace ComInteropDemo
{
    // 首先定义COM可见的接口,必须有唯一的Guid
    [Guid("YOUR-UNIQUE-GUID-HERE-1234-ABCD")] // 生成新的Guid替换这里(可通过VS的Tools>Create Guid生成)
    [ComVisible(true)]
    public interface IComInteropClass
    {
        bool ReadText(out string text);
        bool WriteText(string text);
    }

    /// <summary>
    /// implementation of the method com interface
    /// </summary>
    [Guid("1C9E938A-9BF5-4A42-B795-A4AC2B1E7AC0")]
    [ProgId("Test.Test.ComInteropClass")]
    [ClassInterface(ClassInterfaceType.None)]
    [ComDefaultInterface(typeof(IComInteropClass))]
    [ComVisible(true)]
    public class ComInteropClass : IComInteropClass
    {
        /// <summary>
        /// Reads a text
        /// </summary>
        /// <param name="text">The text (as out parameter)</param>
        /// <returns>true if successful</returns>
        public bool ReadText(out string text)
        {
            text = "Hello from Com Interop";
            return true;
        }

        /// <summary>
        /// Writes a text to a file
        /// </summary>
        /// <param name="text"></param>
        /// <returns>true if successful</returns>
        public bool WriteText(string text)
        {
            string fileName = Path.Combine(Path.GetTempPath(), "ComInteropDemoOutput.txt");
            try
            {
                File.WriteAllText(fileName, text);
            }
            catch (IOException)
            {
                return false;
            }
            return true;
        }
    }
}

关键注意事项

  • 生成唯一Guid:给IComInteropClass生成一个新的Guid(不要和类的Guid重复),可以用Visual Studio的Tools > Create Guid工具选择Registry格式生成。
  • 重新编译与注册:
    1. 重新编译C#项目生成新的.dll文件。
    2. 以管理员身份打开命令提示符,运行regasm命令(替换为你的dll路径):
      regasm /codebase YourComDllName.dll
      
      加上/codebase参数能让COM定位到不在全局程序集缓存(GAC)中的dll文件。

Python测试代码

现在你可以用comtypes正常加载组件并调用方法了:

from comtypes.client import CreateObject

# 创建COM对象
comobject = CreateObject("Test.Test.ComInteropClass")

# 测试ReadText方法
success, text = comobject.ReadText()
if success:
    print(f"ReadText result: {text}")

# 测试WriteText方法
write_success = comobject.WriteText("Hello from Python!")
print(f"WriteText success: {write_success}")

运行后你会看到对应输出,并且可以在系统临时目录(通过%temp%打开)找到ComInteropDemoOutput.txt文件。

内容的提问来源于stack exchange,提问作者vdE

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:41:22