ctypes dll调用在ipython中工作但不在常规python中工作 [英] ctypes dll call works in ipython but not in regular python

查看:697
本文介绍了ctypes dll调用在ipython中工作但不在常规python中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:我的原始问题因为偏离主题而被关闭,但我重新提交了这个问题,并为任何可能遇到类似问题的人提供答案

NOTE: My original question was closed for being off-topic, but I am resubmitting this with an answer for any who might run into a similar issue

我的系统详细信息:

Windows 10 64-bit
Python 3.6 64-bit

我遗憾的是由于机密性而无法共享数据文件或dll,但我使用的是供应商提供的dll(用Delphi编写)读取二进制文件数据文件。我也无权访问源代码,也无权获得详细的编码支持。

I unfortunately cannot share data files or the dll due to confidentiality, but I am using a vendor provided dll (written in Delphi) to read binary instrument data files. I also do not have access to the source code, nor any entitlement to detailed coding support.

下面显示了一个名为filereadtest.py的示例脚本。

A sample script called filereadtest.py is shown below.

import ctypes 

binary_file = r"C:\path\to\binaryfile"
dll_file = r"C:\path\to\dll.dll"
dll = ctypes.WinDLL(dll_file)
dll.OpenDataFile.argtypes = [ctypes.c_wchar_p]
dll.OpenDataFile.restype = ctypes.c_int32
fhandle = dll.OpenDataFile(binary_file)
print(fhandle)
dll.CloseDataFile()

当使用ipython调用时,此调用成功,但是当使用常规python调用时,此调用会产生OSError:

When called with ipython, this call is successful, but when called with regular python, this call gives an OSError:

>>> ipython filereadtest.py
0

>>> python filereadtest.py
Traceback (most recent call last):
  File "filereadtest.py", line 8, in <module>
    fhandle = dll.OpenDataFile(binary_file)
OSError: [WinError 250477278] Windows Error 0xeedfade


推荐答案

IPython导入了很多库,并深埋在该导入树中,一个特定于Windows的标志导入 win32com ,其中反过来导入 pythoncom 。 pythoncom导入加载库 pythoncomXX.dll 。 (XX = 36或python版本号)。在这种情况下,dll依赖于正在加载的库。
http://timgolden.me.uk/pywin32-docs/pythoncom。 html

IPython imports a lot of libraries, and buried deep within that import tree, a windows specific flag imports win32com, which in turn imports pythoncom. The pythoncom import loads the library pythoncomXX.dll. (XX=36 or python version number). In this case the dll depends upon this library being loaded. http://timgolden.me.uk/pywin32-docs/pythoncom.html

以下脚本有效:

import ctypes 
import pythoncom  # necessary for proper function of the dll

binary_file = r"C:\path\to\binaryfile"
dll_file = r"C:\path\to\dll.dll"
dll = ctypes.WinDLL(dll_file)
dll.OpenDataFile.argtypes = [ctypes.c_wchar_p]
dll.OpenDataFile.restype = ctypes.c_int32
fhandle = dll.OpenDataFile(binary_file)
print(fhandle)
dll.CloseDataFile()

这篇关于ctypes dll调用在ipython中工作但不在常规python中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆