Boost Python官方样例(一)
配置环境
$ cat /etc/os-release
NAME="Ubuntu"
VERSION="16.04 LTS (Xenial Xerus)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 16.04 LTS"
VERSION_ID="16.04"
HOME_URL="http://www.ubuntu.com/"
SUPPORT_URL="http://help.ubuntu.com/"
BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"
UBUNTU_CODENAME=xenial
# apt install libboost-python-dev cmake
导出C++函数
创建工程目录
$ mkdir Lesson1
$ cd Lesson1
编写C++函数实现
$ vim greet.cpp
char const* greet()
{
return "hello world";
}
编写Boost.Python文件
$ vim greet_wrapper.cpp
#include <boost/python.hpp>
#include "greet.cpp"
BOOST_PYTHON_MODULE(hello_ext)
{
using namespace boost::python;
def("greet", greet);
}
为库编写CMakeLists.txt
$ vim CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project(greet)
### 此处的动态库名必须和BOOST_PYTHON_MODULE()中定义的保持一致,即最后生成的库必须名为hello_ext.so
set(greetSRC greet_wrapper.cpp)
add_library(hello_ext SHARED ${greetSRC})
set_target_properties(hello_ext PROPERTIES PREFIX "")
#dependencies
INCLUDE(FindPkgConfig)
pkg_check_modules(PYTHON REQUIRED python)
include_directories(/usr/include ${PYTHON_INCLUDE_DIRS})
target_link_libraries(hello_ext boost_python)
编译库
$ mkdir build
$ cd build
$ cmake ..
$ make
运行python测试库文件
### 在build目录下执行,即hello_ext.so存在的目录(可以将so移至其他目录,这样就可以在其他目录下打开python终端)
$ python
>>> import hello_ext
>>> help(hello_ext)
>>> hello_ext.greet()
'hello world'
导出C++类
编写C++类实现
$ vim world.h
#include <string.h>
struct World
{
void set(std::string msg) { this->msg = msg; }
std::string greet() { return msg; }
std::string msg;
};
编写Boost.Python文件
$ vim world_wrapper.cpp
#include <boost/python.hpp>
#include "world.h"
using namespace boost::python;
BOOST_PYTHON_MODULE(hello)
{
class_<World>("World")
.def("greet", &World::greet)
.def("set", &World::set)
;
}
运行python测试库文件
$ python
>>> import hello
>>> planet = hello.World()
>>> planet.set('howdy')
>>> planet.greet()
'howdy'
导出C++类(带构造函数)
编写C++类实现
$ cat world.h
#include <string.h>
struct World
{
World(std::string msg): msg(msg) {} // added constructor
void set(std::string msg) { this->msg = msg; }
std::string greet() { return msg; }
std::string msg;
};
编写Boost.Python文件
$ vim world_wrapper.cpp
#include <boost/python.hpp>
#include "world.h"
using namespace boost::python;
BOOST_PYTHON_MODULE(hello)
{
class_<World>("World", init<std::string>())
.def("greet", &World::greet)
.def("set", &World::set)
;
}
运行python测试库文件
>>> import hello
>>> planet = hello.World("test")
>>> planet.greet()
'test'
导出C++类(带数据成员)
编写C++类实现
$ vim var.h
#include <string.h>
struct Var
{
Var(std::string name) : name(name), value() {}
std::string const name;
float value;
};
编写Boost.Python文件
$ vim var_wrapper.cpp
#include <boost/python.hpp>
#include "var.h"
using namespace boost::python;
BOOST_PYTHON_MODULE(hello)
{
class_<Var>("Var", init<std::string>())
.def_readonly("name", &Var::name)
.def_readwrite("value", &Var::value);
}
运行python测试库文件
>>> import hello
>>> x = hello.Var('pi')
>>> x.value = 3.14
>>> print x.name, 'is around', x.value
pi is around 3.1400001049