我想使用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#定义中定义属性IComInteropClass,但我不知道如何。在这方面的任何帮助将不胜感激!