Pybind11 与 CMake 的联合使用
GitHub 传送门**
由于 Pybind11 官方教程中未找到与 CMake 结合使用的示例,因此记录一下 CMakeLists 的写法。
本教程帮助你在 Python 中调用 CMake 生成的 C++ 函数。理论上,你只需要点进上面的 GitHub 链接即可。
Step 1: 安装 pytest
1 | pip install pytest |
Step 2: 下载 Pybind11 并配置 CMake
你需要将 pybind11 和 CMakeLists.txt 放在同一个文件夹下。可以从 GitHub 官方仓库下载:
1 | git clone https://github.com/pybind/pybind11.git |
然后进入 pybind11 目录并进行编译检查:
1 | mkdir build |
Step 3: 编写示例代码
创建 example.cpp 文件,示例如下:
1 |
|
然后创建 CMakeLists.txt,内容如下:
1 | cmake_minimum_required(VERSION 2.8.12) |
由于 CMakeLists.txt 需要用到 pybind11,所以必须将二者放在同一路径下。
Step 4: CMake 编译
执行以下命令进行编译:
1 | mkdir build |
编译成功后,会生成一个 .so 共享库文件,这是 Python 调用 C++ 代码的关键。
注意: .so 文件需要与 Python 代码放在同一目录下。
Step 5: 测试
可以直接在 Python 终端测试:
1 | import example |
输出:
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