使用.NET注册com对象dll
我实现了一个python com服务器,并使用py2exe工具生成可执行文件和dll。 然后我用regsvr32.exe来注册dll.I得到一个消息,注册成功。然后我尝试在.NET中添加对该dll的引用。我浏览到DLL的位置并选择它,但我得到一个错误消息框,说:无法添加对dll的引用,请确保该文件是可访问的,它是一个有效的程序集或COM组件。下面添加服务器和安装脚本的代码。 我想提一下,我可以运行服务器作为python脚本,并使用后期绑定从.net使用它。 有什么我失踪或做错了?我将不胜感激任何帮助。使用.NET注册com对象dll
感谢, 萨拉
hello.py
import pythoncom
import sys
class HelloWorld:
#pythoncom.frozen = 1
if hasattr(sys, 'importers'):
_reg_class_spec_ = "__main__.HelloWorld"
_reg_clsctx_ = pythoncom.CLSCTX_LOCAL_SERVER
_reg_clsid_ = pythoncom.CreateGuid()
_reg_desc_ = "Python Test COM Server"
_reg_progid_ = "Python.TestServer"
_public_methods_ = ['Hello']
_public_attrs_ = ['softspace', 'noCalls']
_readonly_attrs_ = ['noCalls']
def __init__(self):
self.softspace = 1
self.noCalls = 0
def Hello(self, who):
self.noCalls = self.noCalls + 1
# insert "softspace" number of spaces
print "Hello" + " " * self.softspace + str(who)
return "Hello" + " " * self.softspace + str(who)
if __name__=='__main__':
import sys
if hasattr(sys, 'importers'):
# running as packed executable.
if '--register' in sys.argv[1:] or '--unregister' in sys.argv[1:]:
# --register and --unregister work as usual
import win32com.server.register
win32com.server.register.UseCommandLine(HelloWorld)
else:
# start the server.
from win32com.server import localserver
localserver.main()
else:
import win32com.server.register
win32com.server.register.UseCommandLine(HelloWorld)
setup.py
from distutils.core import setup
import py2exe
setup(com_server = ["hello"])
我会回答我的问题,以帮助任何人可能有类似的问题。我希望这会有所帮助。 我无法在COM选项卡上找到我的服务器,因为.NET(& Visual-Studio)需要带有TLB的COM服务器。但是Python的COM服务器没有TLB。 所以要通过(C#和Late binding)从.NET使用服务器。下面的代码演示如何使这个:
// C#代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Type pythonServer;
object pythonObject;
pythonServer = Type.GetTypeFromProgID("PythonDemos.Utilities");
pythonObject = Activator.CreateInstance(pythonServer);
}
}
} `
行:
_reg_clsid_ = pythoncom.CreateGuid()
创建一个新的GUID每次该文件被调用。您可以创建在命令行上一个GUID:
C:\>python -c "import pythoncom; print pythoncom.CreateGuid()"
{C86B66C2-408E-46EA-845E-71626F94D965}
,然后更改行:
_reg_clsid_ = "{C86B66C2-408E-46EA-845E-71626F94D965}"
进行此更改后,我能运行代码,并与下面的VBScript测试:
Set obj = CreateObject("Python.TestServer")
MsgBox obj.Hello("foo")
我没有MSVC方便看看这是否修复了“添加引用”问题。
感谢您的回答,我遵循您的指南,我注册了服务器没有问题。但我仍然无法在COM选项卡上找到我的服务器。 – Sarah 2009-07-05 22:59:07
谢谢回答,我这样做,在第一,但没有找到我在COM选项卡上的服务器,所以我想我会浏览到它。 – Sarah 2009-07-05 13:04:35