python 使用 CDLL 加载 c lib,在 python 路径中看不到库

标签 python ctypes lammps

我正在尝试让一些开源学术代码正常工作(项目主页是 here )。它是一个带有(非常)薄的 python 包装器的大型 C++ 代码库,它使用 CDLL 加载 C++ 并调用一些可用于允许代码的原始 python 脚本编写的 C 函数。

但是,最初的导入代码崩溃了,因为它无法在站点包中找到它旁边的 .so 文件:

在安装的文件中:

from ctypes import *

try:
  self.lib = CDLL("_lammps.so")
except:
  try:
    self.lib = CDLL("_lammps_serial.so")
  except:
    raise OSError,"Could not load LAMMPS dynamic library"

在脚本或解释器中:

from lammps import lammps
l = lammps()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "lammps.py", line 42, in __init__
    raise OSError,"Could not load LAMMPS dynamic library"
OSError: Could not load LAMMPS dynamic library

其他答案might seem to have this covered ,但这仅在实际调用的脚本(或运行解释器的提示的工作目录)中调用 CDLL() 时才有效 - 即,如果“相对路径”在用户空间中,而不是 python-library-space。

我们如何可靠地安装并导入我们自己构建的 C/C++ 库?除了污染系统库位置,例如 /usr/lib,这不是很 pythonic,我看不到一个简单的解决方案。

(编辑:更正的函数名称,不清楚的重构没有帮助!抱歉!)

最佳答案

我在 linux 上,我为解决这个问题所做的一切都放在了 os 模块的绝对路径中,并且它有效

from ctypes import *
import os

xss = cdll.LoadLibrary(os.path.abspath("libxss.so.1"))
print xss.xss_test_1()

这也是 python 2.7。

关于python 使用 CDLL 加载 c lib,在 python 路径中看不到库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9143440/

相关文章:

python - PIL 从图像中删除背景图像

python - 我们如何在 polars 中对时间序列进行重新采样

python - 在 Windows 上的 Python 中获取上次更改时间

python - 如何从 Python 与 MATLAB 交互?

c++ - 如何调试从 gdb 中的脚本获取输入的 C++ 程序

Python 多处理问题?

python - 将元组附加到列表

python - numpy 通过 ctypes 调用 sse2

c++ - CMake:使用相同的代码但包含不同的包含路径构建多个库