问题
windows 下python 需要加载不同功能的dll库,我按照dll功能放置在多个目录下,发现无法加载成功。
过程
我本人的机器是使用Anaconda(python3.9) 的环境,通过在入口设置:
os.environ[‘path’] += r";./lib/lib_ws"
os.environ[‘path’] += r";./lib/lib_win"
这种方式设置了进程的临时环境变量,在加载dll库时,使用方法
_libws = cdll.LoadLibrary(‘libws.dll’)
就可以正常加载dll库。
但我把代码更新上库后,我的一个同事就是无法正常加载该库。
经过定位,我同事没有使用Anaconda ,而是使用python3.9的开发环境,虽然都是使用python3.9,但是我对比了
/lib/ctypes/init.py 下两个的实现,发现Anaconda 下明显多了mode的设置:
if _os.name == "nt":
if winmode is not None:
mode = winmode
else:
import nt
mode = nt._LOAD_LIBRARY_SEARCH_DEFAULT_DIRS
if '/' in name or '\\' in name:
self._name = nt._getfullpathname(self._name)
mode |= nt._LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR
# PATH is how DLL lookup has always worked in the past
# in Python on Windows. IMHO both the above mode flags
# are not wanted and cause many serious regressions within
# the conda ecosystem on Windows. We should however
# propagate any PATH changes that have happened to Python
# library and that is not yet implemented.
LOAD_WITH_ALTERED_SEARCH_PATH = 0x00000008
mode = LOAD_WITH_ALTERED_SEARCH_PATH
解决
将如上代码替换到 python3.9环境下的__init__.py 文件,问题解决。
这样我就不需要把所有的dll库都放在一个目录下了。