从Python访问COM互操作

2024-09-30 18:20:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我想访问Python中用c#编写的COM互操作功能。我用c#编写了以下代码,它定义了COM互操作功能,并编译为.dll,使用regasm.exe注册。这似乎很有效

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace ComInteropDemo
{
    /// <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;
        }
    }
}

问题是,我想从python(客户端)访问COM互操作功能,我尝试使用comtypes库来实现这一点,并尝试使用以下代码加载COM互操作演示:

from comtypes.client import CreateObject

comobject = CreateObject("Test.Test.ComInteropClass")

问题是,它抛出一个错误,表示: “AttributeError:模块'comtypes.gen.ComInteropDemo'没有'IComInteropClass'属性”

似乎我必须在COM功能的c#定义中定义属性ICominetRopClass,但我不知道如何定义。在此方面的任何帮助都将不胜感激


Tags: texttest功能comtruestring定义param