Python ctypes:从相对路径加载DLL [英] Python ctypes: loading DLL from from a relative path
问题描述
我有一个Python模块 wrapper.py
,该模块包装了一个C DLL。 DLL位于与模块相同的文件夹中。因此,我使用以下代码加载它:
I have a Python module, wrapper.py
, that wraps a C DLL. The DLL lies in the same folder as the module. Therefore, I use the following code to load it:
myDll = ctypes.CDLL("MyCDLL.dll")
如果我从自己执行 wrapper.py
夹。但是,如果我从其他地方运行它,它将失败。那是因为ctypes计算相对于当前工作目录的路径。
This works if I execute wrapper.py
from its own folder. If, however, I run it from elsewhere, it fails. That's because ctypes computes the path relative to the current working directory.
我的问题是,有没有一种方法可以指定DLL相对于包装器的路径而不是当前的工作目录?这样一来,我就可以将两者一起运送,并允许用户从任何地方运行/导入包装器。
My question is, is there a way by which I can specify the DLL's path relative to the wrapper instead of the current working directory? That will enable me to ship the two together and allow the user to run/import the wrapper from anywhere.
推荐答案
os.path.dirname(__ file __)
获取Python源文件所在的目录。
You can use os.path.dirname(__file__)
to get the directory where the Python source file is located.
这篇关于Python ctypes:从相对路径加载DLL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!