使用pybind11可将C++代码封装为Python模块,通过编写绑定代码并编译为共享库,实现高效调用。首先安装pybind11并获取头文件路径,然后在C++中定义函数和类,并使用PYBIND11_MODULE宏导出;接着通过g++或CMake编译生成模块文件;最后在Python中直接导入使用。支持STL容器、异常映射、默认参数及NumPy集成等高级特性,使C++功能在Python中如原生模块般运行。

用 C++ 结合 pybind11 封装库供 Python 调用,是实现高性能混合编程的常用方式。pybind11 是一个轻量级头文件库,能将 C++ 函数、类、变量等自然地暴露给 Python,且语法简洁,兼容 C++11 及以上标准。
使用 pybind11 前需确保已安装。推荐通过 pip 安装:
pip install pybind11
开发时还需包含其头文件。若通过 pip 安装,可通过以下命令查看头文件路径:
立即学习“Python免费学习笔记(深入)”;
python -m pybind11 --includes
该命令输出编译时需添加的 include 路径,如 -I/usr/include/python3.8 和 -I/path/to/pybind11/include。
创建一个 C++ 文件(例如 example.cpp),封装一个加法函数和一个简单类:
#include <pybind11/pybind11.h>
#include <string>
<p>int add(int a, int b) {
return a + b;
}</p><p>class Calculator {
public:
explicit Calculator(const std::string& name) : name<em>(name) {}
int multiply(int x, int y) {
return x * y;
}
std::string greet() const {
return "Hello from " + name</em>;
}
private:
std::string name_;
};</p><p>// 绑定模块
PYBIND11_MODULE(example, m) {
m.doc() = "A simple example module";</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">// 绑定函数
m.def("add", &add, "A function that adds two integers");
// 绑定类
pybind11::class_<Calculator>(m, "Calculator")
.def(pybind11::init<const std::string&>())
.def("multiply", &Calculator::multiply)
.def("greet", &Calculator::greet);}
需要将 C++ 代码编译为 Python 可导入的共享库(.so 或 .pyd)。可使用 g++ 手动编译或借助 CMake。
方法一:使用 g++ 直接编译(适用于简单项目)
g++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix`
说明:
方法二:使用 CMake(推荐用于复杂项目)
创建 CMakeLists.txt:
cmake_minimum_required(VERSION 3.10) project(example) <p>find_package(pybind11 REQUIRED)</p><p>pybind11_add_module(example example.cpp)
然后执行:
mkdir build && cd build cmake .. && make
编译成功后,当前目录会生成 example.so(Linux/macOS)或 example.pyd(Windows)。在 Python 中直接导入:
import example
<p>print(example.add(2, 3)) # 输出: 5</p><p>calc = example.Calculator("MyCalc")
print(calc.greet()) # 输出: Hello from MyCalc
print(calc.multiply(4, 5)) # 输出: 20pybind11 支持更多功能,如:
例如,支持 vector 的函数:
#include <pybind11/stl.h>
#include <vector>
<p>std::vector<int> filter_positive(const std::vector<int>& input) {
std::vector<int> result;
for (int x : input)
if (x > 0) result.push_back(x);
return result;
}</p><p>// 在 PYBIND11_MODULE 中添加
m.def("filter_positive", &filter_positive);Python 中可直接传 list,返回 list。
基本上就这些。只要写好绑定代码,编译正确,就能在 Python 中像原生模块一样使用 C++ 功能。不复杂但容易忽略细节,比如文件命名和编译选项。
以上就是c++++怎么使用pybind11来封装库给Python调用_c++与Python混合编程接口开发教程的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号