我在C#.NET中调用Python COM对象时遇到问题。感谢任何帮助。
我创建了一个Python COM服务器,如下所示:
import pythoncom
import sys
class HelloWorldUtilities:
_reg_desc_ = "Python Test COM Server"
_reg_progid_ = "Python.TestServer"
_reg_clsid_ = '{07CCE0CC-EB69-41D6-B6B8-67E5D31AF229}'
_public_methods_ = ['Hello']
_public_attrs_ = ['noOfCalls']
_readonly_attrs_ = ['noOfCalls']
def __init__(self):
self.noOfCalls = 0
def Hello(self,who):
self.noOfCalls+=1
return "Hello " + str(who)
if __name__ == '__main__':
if "--register" in sys.argv[1:] or "--unregister" in sys.argv[1:]:
print ("Registering COM Server")
import win32com.server.register
win32com.server.register.UseCommandLine(HelloWorldUtilities)
else:
from win32com.server import localserver
localserver.serve(['{07CCE0CC-EB69-41D6-B6B8-67E5D31AF229}'])
我注册服务器时得到的o / p是:
C:\PythonProjects>python HelloWorldCOM.py --register
Registering COM Server
Requesting elevation and retrying...
Registering COM Server
Registered: Python.TestServer
然后我按如下方式运行服务器:
C:\PythonProjects>python HelloWorldCOM.py
现在,我遇到的问题是我似乎无法在C#.NET中调用Python COM对象
无法在C#项目的可用COM组件列表中查看已注册的COM对象,例如,当我转到References-> RightClick->添加引用 - > COM,我在这里找不到Python COM对象
我也尝试过后期绑定:
class Program
{
static void Main(string[] args)
{
try
{
Type typeServer = Type.GetTypeFromProgID("Python.TestServer");
object instance = Activator.CreateInstance(typeServer, true);
if (instance != null)
{
Type type = instance.GetType();
string who = "Praveen";
object[] paramList = { who };
object objReturn = type.InvokeMember("Hello",
BindingFlags.Default | BindingFlags.InvokeMethod,
null,
instance,
paramList);
string result = (string)objReturn;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
似乎正确地获得服务器类型,如
Type typeServer = Type.GetTypeFromProgID("Python.TestServer");
然而,当程序执行时,程序会在下一行中突然退出
object instance = Activator.CreateInstance(typeServer, true);
但没有抛出异常。输出窗口显示以下内容:
The program '[2596] TestPyCOM1.vshost.exe' has exited with code 3 (0x3).
感谢您的任何帮助,或者如果您能让我知道从C#.NET调用Python COM对象的另一种方法。
感谢。