0.pybind11简介
pybind11是一个轻量级的头文件库,它在Python中公开c++类型,反之亦然,主要用于创建现有c++代码的Python绑定。
简而言之,pybind11是用于实现Python调用c++代码的相对好用的工具。
1.下载pybind11
git clone https://github.com/pybind/pybind11.git --depth=1
2.编写cpp代码
编写example.cpp
文件内容如下:
#include <pybind11/pybind11.h>
namespace py = pybind11;
int add(int i, int j)
{
return i + j;
}
int sub(int i, int j)
{
return i - j;
}
int multiply(int i, int j)
{
return i * j;
}
PYBIND11_MODULE(example, m)
{
m.doc() = "pybind11 example plugin"; // 可选的模块说明
m.def("add", &add, "A function which adds two numbers");
m.def("sub", &sub, "A function which subs two numbers");
m.def("multiply", &multiply, "A function which multiplies two numbers");
}
3.使用CMake编译生成库文件
3.1 编写CMakeLists.txt
文件
编写CMakeLists.txt
文件,内容如下:
cmake_minimum_required(VERSION 3.11)
project(learnPybind11)
add_subdirectory(pybind11)
pybind11_add_module(example example.cpp)
3.2 使用cmake和make命令生成库文件
mkdir build
cmake ..
make
4.项目整体目录
(base) ➜ learnPybind11 ls
build CMakeLists.txt example.cpp pybind11
(base) ➜ learnPybind11 tree -L 1
.
├── build
├── CMakeLists.txt
├── example.cpp
└── pybind11
2 directories, 2 files
(base) ➜ learnPybind11 tree -L 2
.
├── build
│ ├── CMakeCache.txt
│ ├── CMakeFiles
│ ├── cmake_install.cmake
│ ├── example.cpython-38-x86_64-linux-gnu.so
│ ├── Makefile
│ └── pybind11
├── CMakeLists.txt
├── example.cpp
└── pybind11
├── build
├── CMakeFiles
├── cmake_install.cmake
├── CMakeLists.txt
├── docs
├── include
├── LICENSE
├── Makefile
├── MANIFEST.in
├── pybind11
├── pyproject.toml
├── README.rst
├── setup.cfg
├── setup.py
├── tests
└── tools
11 directories, 15 files
5.测试
(base) ➜ build pwd
/root/Projects/CppProjects/learnPybind11/build
(base) ➜ build python
Python 3.8.3 (default, May 19 2020, 18:47:26)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import example
>>> dir(example)
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'add', 'multiply', 'sub']
>>> example.add(3,4)
7
>>> exit()