如何使用 Boost.Python

How to use Boost.Python

本文关键字:Python Boost 何使用      更新时间:2023-10-16

我最近才发现了Boost.Python,我试图弄清楚它是如何工作的。我尝试在官方网站上浏览教程。但是,我得到了

link.jam: No such file or directory

当像示例中一样运行 bjam 时(这似乎只是一个警告),和

Traceback (most recent call last):
File "hello.py", line 7, in <module>
import hello_ext
ImportError: libboost_python.so.1.55.0: cannot open shared object file: No such file or directory

运行 Python hello.py 时。

我还尝试编译一个模块,如另一个教程中所述,结果类似。我正在运行 Ubuntu14.04,自己编译了 boost1.55。


我尝试编译以下内容:

#include <boost/python.hpp>
char const* greet()
{
    return "hello, world";
}
BOOST_PYTHON_MODULE(hello_ext)
{
    using namespace boost::python;
    def("greet", greet);
}

从命令行使用以下命令:

g++ -o hello_ext.so hello.cpp -I /usr/include/python2.7/ -I /home/berardo/boost_1_55_0/ -L /usr/lib/python2.7/ -L /home/berardo/boost/lib/ -lboost_python -lpython2.7 -Wl, -fPIC -expose-dynamic 

这仍然给了我一个:

/usr/bin/ld: impossibile trovare : File o directory non esistente
collect2: error: ld returned 1 exit status.

最后,我能够让它工作。首先,我按照Dan的建议修复了链接器问题。它最终编译了,但我仍然得到:

ImportError: libboost_python.so.1.55.0: cannot open shared object file: No such file or directory

问题是 python 模块无法正确加载,所以我需要添加另一个链接器选项。在这里,我报告最终的制作文件:

# location of the Python header file
PYTHON_VERSION = 2.7
PYTHON_INCLUDE = /usr/include/python$(PYTHON_VERSION)
# location of the Boost Python include files and library
BOOST_INC = ${HOME}/boost/include
BOOST_LIB = ${HOME}/boost/lib
# compile mesh classes
TARGET = hello_ext
$(TARGET).so: $(TARGET).o
    g++ -shared -Wl,-rpath,$(BOOST_LIB) -Wl,--export-dynamic $(TARGET).o -L$(BOOST_LIB) -lboost_python -L/usr/lib/python$(PYTHON_VERSION)/config -lpython$(PYTHON_VERSION) -o $(TARGET).so
$(TARGET).o: $(TARGET).C
    g++ -I$(PYTHON_INCLUDE) -I$(BOOST_INC) -fPIC -c $(TARGET).C

请注意 -wl,-rpath 选项,它显然使新创建的共享库可用于 python 脚本。
@Dan:感谢您的宝贵提示。