无法使用ctypes在python中加载dll [英] cannot load dll in python with ctypes

查看:47
本文介绍了无法使用ctypes在python中加载dll的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ctypes加载dll形式的python代码,这引发了错误.

I am trying to load a dll form python code with ctypes and it raised an error.

我的python代码:

import ctypes
from ctypes import *
hllDll = ctypes.WinDLL ("c:\\Users\\saar\\Desktop\\pythonTest\\check.dll")

,并且出现了此错误:

Traceback (most recent call last): 
  File "C:\AI\PythonProject\check.py", line 5, in <module> 
    hllDll = ctypes.WinDLL("c:\\Users\\saar\\Desktop\\pythonTest\\check.dll") 
  File "C:\Python27\lib\ctypes\__init__.py", line 365, in __init__ 
    self._handle = _dlopen(self._name, mode) 
WindowsError: [Error 126] The specified module could not be found 

我用google搜索它,我看到的每一篇指南都用两个反斜杠写了dll路径,或导入ctypes,然后输入:from ctypes import *.

I google it and every post i saw guide to write the dll path with two backslash, or import ctypes and then write : from ctypes import *.

推荐答案

check.dll 可能在文件夹中具有依赖关系,因此在使用它之前,用户可以先调用 os.chdir设置工作目录,例如:

The check.dll might have dependencies in the folder so prior to using it, use could first call os.chdir to set the working directory, for example:

import ctypes
import os

os.chdir(r'c:\Users\saar\Desktop\pythonTest')
check = ctypes.WinDLL(r'c:\Users\saar\Desktop\pythonTest\check.dll')

您可以通过在路径字符串前面加上 r 来避免两个反斜杠.

You can avoid needing two backslashes by prefixing your path string with r.

或者,可以通过 win32api 使用 LoadLibraryEx 来获取句柄并将其传递给WinDLL,如下所示:

Alternatively, LoadLibraryEx can be used via win32api to get the handle and pass it to WinDLL as follows:

import ctypes
import win32api
import win32con

dll_name = r'c:\Users\saar\Desktop\pythonTest\check.dll'
dll_handle = win32api.LoadLibraryEx(dll_name, 0, win32con.LOAD_WITH_ALTERED_SEARCH_PATH)
check = ctypes.WinDLL(dll_name, handle=dll_handle)

Microsoft已经开发了一个名为 depends.exe 的DLL依赖项检查器,但是很不幸,很久以前它停止了进一步的开发.尽管现在有其他类似的实用程序也可以执行相同的操作.这个想法是,如果您尝试加载DLL,但是它需要另一个您没有的DLL才能工作,则DLL加载会失败而没有给出明显的原因.通过使用这些工具,您可以找到问题所在.

Microsoft had developed a DLL dependency checker called depends.exe but unfortunately stopped further development of this a long time ago. There are though now other similar utilities which do the same. The idea is that if you are trying to load your DLL, but it requires a another DLL to work which you don't have, the DLL load will fail without giving an obvious reason. By using these tools you can locate where the problem is.

Microsoft建议使用github上可用的依赖关系.

Microsoft recommend using Dependencies which is available on github.

这篇关于无法使用ctypes在python中加载dll的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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