我正在尝试让一些开源学术代码正常工作(项目主页是 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/