Python编写的com组件发生R6034错误的原因与解决办法
原因
导致Python编写的com组件发生R6034错误的原因是使用到了不兼容的C++运行时库,具体来说是Python使用了某些版本的Microsoft Visual C++ Redistributable运行时库,而我们在使用该COM组件时,却在环境变量中设置了另外一个版本的运行时库,如下所示:
R6034 An application has made an attempt to load the C runtime library incorrectly. Please contact the application's support team for more information.
解决方案
解决方案是需要在安装Python时,安装所用的Microsoft Visual C++ Redistributable运行时库,并将其路径添加到系统环境变量中。另外,还需要将这些运行时库的路径添加到Python编写的com组件的.manifest文件中。
以下是两个示例:
示例一
使用Python编写一个简单的com组件,代码如下:
import win32com.server.register
class HelloWorld:
_reg_clsid_ = "{995EE449-5C51-4F60-83E0-97925D287B9B}"
_reg_desc_ = "Python Sample COM Server"
_reg_progid_ = "Python.Sample.Srv"
_public_methods_ = ["hello"]
_public_attrs_ = []
_readonly_attrs_ = []
def hello(self):
return "Hello, World!"
def register(server=None):
if server is None:
import win32com.server.register
server = win32com.server.register.UseCommandLine
win32com.server.register.RegisterServer(HelloWorld)
print("Server registered successfully")
if __name__ == "__main__":
register()
运行这个脚本,它会生成一个COM组件的单独的.manifest文件,并将该文件存储在与COM组件同一目录中。可以使用Visual Studio打开这个.manifest文件,然后找到其Windows库依赖项,如下所示:
<dependency>
<dependentAssembly>
<assemblyIdentity type="win32" name="Microsoft.VC90.CRT" version="9.0.21022.8" processorArchitecture="*" publicKeyToken="1fc8b3b9a1e18e3b" />
</dependentAssembly>
</dependency>
在使用该COM组件时,需要确保该库可以找到,可以在环境变量中设置该库的路径,或将该库拷贝到系统目录中。
示例二
另一个示例是关于Python 3.7和64位Windows 7之间的问题。Python 3.7默认使用Visual Studio 2017编译器,并且必须依赖于Microsoft Visual C++ 2017 Redistributable运行时库,但不是所有的Windows 7系统都支持这个库。如果出现此类问题,我们可以使用早期版本的Microsoft Visual C++ Redistributable运行时库解决问题,但要注意,必须与使用的编译器版本匹配。
在这种情况下,需要使用以下命令将所需的Microsoft Visual C++ Redistributable运行时库安装到Python的环境中:
C:\Users\user\Downloads>python -m pip install --upgrade pip
C:\Users\user\Downloads>pip install pypiwin32
C:\Users\user\Downloads>pywin32_postinstall.py -install
以上命令将添加早期版本的Microsoft Visual C++ Redistributable运行时库到Python 3.7的环境,然后使用COM组件之前需要先将这些运行时库的路径添加到Python编写的com组件的.manifest文件中。
综上所述,解决方案是安装适当的Microsoft Visual C++ Redistributable运行时库,并将其路径添加到系统环境变量中,然后将库路径添加到Python编写的com组件的.manifest文件中,以保证COM组件的正常运行。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python编写的com组件发生R6034错误的原因与解决办法 - Python技术站