前一篇blog写了pybind11的hello world例子,编译出了一个非常简单的example.so作为python库。这一篇写一个功能相同的、用boost.python实现的版本,用来对照。
首先安装依赖/配环境:
- 安装miniconda3,用来弄python环境,这里是python3.7.4
- conda install py-boost,这里安装了boost-1.67和对应的python包
- cmake 3.15版本或更高
src/example.cpp
#include <boost/python.hpp>
#include <iostream>
#include <stdio.h>
using namespace boost::python;
const char* greet()
{
return "hello, world";
}
int add(int i, int j) {
return i+j;
}
BOOST_PYTHON_MODULE(example)
{
scope().attr("__doc__") = "boost.python example plugin";
def("greet", greet);
def("add", &add, "A function which adds two numbers");
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.14)
project(example)
#set(Boost_NO_BOOST_CMAKE ON)
set(BOOST_INCLUDEDIR "/home/zz/soft/miniconda3/include" CACHE PATH "")
set(PYTHON_INCLUDE_DIR "/home/zz/soft/miniconda3/include/python3.7m" CACHE PATH "")
find_package(Boost REQUIRED COMPONENTS python37)
add_library(example SHARED src/example.cpp)
set_target_properties(example PROPERTIES PREFIX "" OUTPUT_NAME "example")
target_link_libraries(example Boost::python37)
target_include_directories(example PRIVATE ${PYTHON_INCLUDE_DIR})
编译运行记录:
(base) arcsoft-43% cd build
(base) arcsoft-43% ls
(base) arcsoft-43% cmake ..
-- The C compiler identification is GNU 5.4.0
-- The CXX compiler identification is GNU 5.4.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
m-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
a-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
ke
-- Found Boost: /home/zz/soft/miniconda3/include (found version "1.67.0") found components: python37
-- Configuring done
-- Generating done
-- Build files have been written to: /home/zz/work/test/boost_python_demo/build
(base) arcsoft-43% make
Scanning dependencies of target example
[ 50%] Building CXX object CMakeFiles/example.dir/src/example.cpp.o
[100%] Linking CXX shared library example.so
[100%] Built target example
(base) arcsoft-43% python
Python 3.7.3 (default, Mar 27 2019, 22:11:17)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import example
>>> example.__doc__
'boost.python example plugin'
>>> example.add(1,3)
4
>>> example.greet()
'hello, world'
参考
https://wiki.python.org/moin/boost.python/module
pybind11可以直接用doc()
函数,boost.python必须搞一个scope().doc()
网友评论