Pybind11 与 CMake 的联合使用

Newsun Lv1

GitHub 传送门**
由于 Pybind11 官方教程中未找到与 CMake 结合使用的示例,因此记录一下 CMakeLists 的写法。

本教程帮助你在 Python 中调用 CMake 生成的 C++ 函数。理论上,你只需要点进上面的 GitHub 链接即可。


Step 1: 安装 pytest

1
pip install pytest

Step 2: 下载 Pybind11 并配置 CMake

你需要将 pybind11CMakeLists.txt 放在同一个文件夹下。可以从 GitHub 官方仓库下载:

1
git clone https://github.com/pybind/pybind11.git

然后进入 pybind11 目录并进行编译检查:

1
2
3
4
mkdir build
cd build
cmake ..
cmake --build . --config Release --target check

Step 3: 编写示例代码

创建 example.cpp 文件,示例如下:

1
2
3
4
5
6
7
8
9
10
11
12
#include <pybind11/pybind11.h>
namespace py = pybind11;

int add(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");
}

然后创建 CMakeLists.txt,内容如下:

1
2
3
4
5
cmake_minimum_required(VERSION 2.8.12)
project(example)

add_subdirectory(pybind11)
pybind11_add_module(example example.cpp)

由于 CMakeLists.txt 需要用到 pybind11,所以必须将二者放在同一路径下。


Step 4: CMake 编译

执行以下命令进行编译:

1
2
3
4
mkdir build
cd build
cmake ..
make

编译成功后,会生成一个 .so 共享库文件,这是 Python 调用 C++ 代码的关键。
注意: .so 文件需要与 Python 代码放在同一目录下。


Step 5: 测试

可以直接在 Python 终端测试:

1
2
import example
example.add(3, 4)

输出:

1
7
  • Title: Pybind11 与 CMake 的联合使用
  • Author: Newsun
  • Created at : 2025-03-06 14:13:19
  • Updated at : 2025-03-06 06:40:09
  • Link: https://redefine.ohevan.com/2025/03/06/pybind11-CMake/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments