简体   繁体   English

Python ctypes:从相对路径加载DLL

[英]Python ctypes: loading DLL from from a relative path

I have a Python module, wrapper.py , that wraps a C DLL. 我有一个包装C DLL的Python模块wrapper.py The DLL lies in the same folder as the module. DLL与模块位于同一文件夹中。 Therefore, I use the following code to load it: 因此,我使用以下代码加载它:

myDll = ctypes.CDLL("MyCDLL.dll")

This works if I execute wrapper.py from its own folder. 如果我从自己的文件夹中执行wrapper.py ,这是有效的。 If, however, I run it from elsewhere, it fails. 但是,如果我从其他地方运行它,它就会失败。 That's because ctypes computes the path relative to the current working directory. 那是因为ctypes计算相对于当前工作目录的路径。

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? 我的问题是,有没有一种方法可以指定相对于包装器而不是当前工作目录的DLL路径? 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源文件所在的目录。

Expanding on Matthew's answer: 扩展马修的答案:

import os.path
dll_name = "MyCDLL.dll"
dllabspath = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + dll_name
myDll = ctypes.CDLL(dllabspath)

This will only work from a script, not the console nor from py2exe . 这只能从脚本,而不是控制台或py2exe

I always add the directory where my DLL is to the path. 我总是将我的DLL所在的目录添加到路径中。 That works: 这样可行:

os.environ['PATH'] = os.path.dirname(__file__) + ';' + os.environ['PATH']
windll.LoadLibrary('mydll.dll')

Note that if you use py2exe, this doesn't work (because __file__ isn't set). 请注意,如果使用py2exe,则不起作用(因为未设置__file__ )。 In that case, you need to rely on the sys.executable attribute (full instructions at http://www.py2exe.org/index.cgi/WhereAmI ) 在这种情况下,您需要依赖sys.executable属性( http://www.py2exe.org/index.cgi/WhereAmI上的完整说明)

Another version: 另一个版本:

dll_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'MyCDLL.dll')
myDll = ctypes.CDLL(dll_file)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM