[英]Error when loading .dll from a different directory using python ctypes.CDLL()
I have to following directory structure: 我必须遵循目录结构:
MainProject
| ...project files
| rtlsdr\
| | rtlsdr.dll
| | ...other .dll's etc.
I am using the function CDLL() in the library ctypes to load rtlsdr.dll
. 我在库ctypes中使用函数CDLL()来加载rtlsdr.dll
。 It works fine when my working directory is rtlsdr\\
: 当我的工作目录是rtlsdr\\
时,它工作正常:
$ cd rtlsdr
$ python
> from ctypes import *
> d = CDLL('rtlsdr.dll')
However, when I try to load the file from another directory: 但是,当我尝试从另一个目录加载文件时:
$ cd MainProject
$ python
> from ctypes import *
> d = CDLL('rtlsdr\\rtlsdr.dll')
I get an error: 我收到一个错误:
WindowsError: [Error 126] The specified module could not be found.
What is the problem here? 这里有什么问题?
A DLL
may have other DLL dependencies that are not in the working directory or the system path. DLL
可能具有不在工作目录或系统路径中的其他DLL依赖项。 Therefore the system has no way of finding those dependencies if not specified explicitly. 因此,如果未明确指定,系统无法找到这些依赖项。 The best way I found is to add the location of the directory containing dependencies to the system path: 我找到的最好方法是将包含依赖项的目录的位置添加到系统路径:
import os
from ctypes import *
abs_path_to_rtlsdr = 'C:\\something\\...\\rtlsdr'
os.environ['PATH'] = abs_path_to_rtlsdr + os.pathsep + os.environ['PATH']
d = CDLL('rtlsdr.dll')
Once the current session is closed, the PATH
variable will return to its original state. 当前会话关闭后, PATH
变量将返回其原始状态。
Another option is to change working directory, but that might affect other module imports: 另一种选择是更改工作目录,但这可能会影响其他模块导入:
import os
os.chdir(abs_path_to_rtlsdr)
# load dll etc...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.