Boost学习笔记

notes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
whereis python3  # /usr/bin/python3.5m
sudo apt install python3-dev # 此命令会安装python3相关头文件到/usr/include/python3*下

tar -xzvf boost_1_76_0.tar.gz
rm boost_1_76_0.tar.gz
cd boost_1_76_0/
sudo bootstrap.sh

# 这里需要配置 project_config
# 不进行此配置时的报错为:
# No python installation configured and autoconfiguration failed. See
# http://www.boost.org/libs/python/doc/building.html for configuration
# instructions or pass --without-python to suppress this message and
# silently skip all Boost.Python targets

vim project_config.jam
# 添加以下内容到 project-config-jam 结尾,注意配置文件中的空格不能省略
# Python configuration
# executable path : header path : library path
using python : 3.5 : /usr/bin/python3.5m : /usr/include/python3.5m : /usr/lib/python3.5 ;

sudo ./b2 # compile
sudo ./b2 install --with-python # install
# 可以在默认编译路径/usr/local/lib下找到相关的libboost*.so
# boost在/usr/local/include/boost下

mkdir demo_boost
cd demo_boost
vim test.cpp
1
2
3
4
5
6
7
8
9
10
11
// test.cpp
#include <boost/python.hpp>

char const* greet() {
return "hello, world";
}

BOOST_PYTHON_MODULE(test) {
using namespace boost::python;
def("greet", greet);
}
1
2
3
4
5
6
7
8
9
# 将/usr/local/lib添加到动态链接库查找路径中,否则链接时会出错 cannot find -lboost_python35

sudo vim /etc/ld.so.conf
# 添加以下内容到结尾
/usr/local/lib

sudo ldconfig
g++ -I/usr/include/python3.5m -fPIC test.cpp -lboost_python35 -shared -o test.so
vim test_py.py
1
2
3
4
5
# test_py.py
import test

print(dir(test))
print(test.greet())
1
python3 test_py.py

另一个例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// demo.cpp
#include <boost/python.hpp>
#include <iostream>
#include <string>

class Bonjour
{
// Private attribute
std::string m_msg;
public:
// Constructor
Bonjour(std::string msg) :m_msg(msg) { }

// Destructor
~Bonjour() { std::cout << "destructed " << this << std::endl; }

// Methods
void greet() { std::cout << m_msg << std::endl; }

// Getter/Setter functions for the attribute
void set_msg(std::string msg) { this->m_msg = msg; }
std::string get_msg() const { return m_msg; }
};

BOOST_PYTHON_MODULE(demo)
{
using namespace boost::python;
class_<Bonjour>("Bonjour", init<std::string>())
.def("greet", &Bonjour::greet)
.add_property("msg", &Bonjour::get_msg, &Bonjour::set_msg);
}

references

tar解压缩命令:[linux tar.gz zip 解压缩 压缩命令

安装与编译linux下安装boost python详解

编译Linux 编译boost (for python3)

动态库问题cannot open shared object file: No such file or directory解决方法

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×