ctypes dll call works in ipython but not in regular python

£可爱£侵袭症+ 提交于 2019-12-24 07:27:08

问题


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


My system details:

Windows 10 64-bit
Python 3.6 64-bit

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.

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

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

回答1:


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

The following script works:

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


来源:https://stackoverflow.com/questions/49266538/ctypes-dll-call-works-in-ipython-but-not-in-regular-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!