ctypes dll调用在ipython中工作,但不在常规python中

时间:2018-03-13 22:00:28

标签: python windows dll ipython ctypes

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

我的系统详情:

Windows 10 64-bit
Python 3.6 64-bit

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

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

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:

>>> 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

1 个答案:

答案 0 :(得分:3)

IPython导入了很多库,并深埋在该导入树中,一个特定于Windows的标志导入win32com,后者又导入pythoncom。 pythoncom导入加载库pythoncomXX.dll。 (XX = 36或python版本号)。在这种情况下,dll依赖于正在加载的库。 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()