pybind11_examples实战:01_py-list_cpp-vector教你实现Python列表与C++向量互转
【免费下载链接】pybind11_examplesExamples for the usage of "pybind11"项目地址: https://gitcode.com/gh_mirrors/py/pybind11_examples
pybind11_examples是一个专注于展示pybind11用法的示例项目,通过实际案例帮助开发者掌握Python与C++之间的数据交互技巧。本文将以01_py-list_cpp-vector模块为例,详细讲解如何实现Python列表与C++向量的高效互转。
为什么需要Python与C++数据互转?
在实际开发中,Python以其简洁易用的特性适合快速开发和数据处理,而C++则在性能敏感场景中表现卓越。pybind11作为连接两者的桥梁,能够让开发者充分发挥两种语言的优势。01_py-list_cpp-vector模块正是这一理念的最佳实践,它展示了最基础也最常用的列表/向量数据转换功能。
核心实现原理
C++端代码解析
在example.cpp中,我们可以看到完整的实现逻辑:
首先通过头文件引入必要的依赖:
#include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <vector>其中<pybind11/stl.h>是实现STL容器与Python数据结构自动转换的关键。
核心功能函数modify接收C++向量并返回新的向量:
std::vector<double> modify(const std::vector<double>& input) { std::vector<double> output; std::transform( input.begin(), input.end(), std::back_inserter(output), [](double x) -> double { return 2.*x; } ); return output; }最后通过pybind11暴露接口:
PYBIND11_MODULE(example,m) { m.doc() = "pybind11 example plugin"; m.def("modify", &modify, "Multiply all entries of a list by 2.0"); }Python端调用示例
test.py展示了如何在Python中使用这个C++扩展:
import example A = [1.,2.,3.,4.] B = example.modify(A) print(B) # 输出 [2.0, 4.0, 6.0, 8.0]整个过程中,Python列表A会自动转换为C++的std::vector<double>,处理完成后又会自动转换回Python列表,开发者无需关心底层转换细节。
编译配置说明
模块的编译配置在CMakeLists.txt中定义:
add_subdirectory(pybind11) pybind11_add_module(example example.cpp)这两行简单的配置就完成了C++扩展模块的编译设置,pybind11会自动处理所有复杂的编译链接细节。
快速上手步骤
- 克隆仓库:
git clone https://gitcode.com/gh_mirrors/py/pybind11_examples- 进入示例目录:
cd pybind11_examples/01_py-list_cpp-vector- 编译构建:
mkdir build && cd build cmake .. make- 运行测试:
python test.py常见问题解决
- 转换失败:确保包含了
<pybind11/stl.h>头文件,这是STL容器转换的基础 - 数据类型不匹配:目前示例支持double类型,如需其他类型可修改模板参数
- 编译错误:检查pybind11子模块是否正确克隆,可通过
git submodule update --init更新
通过01_py-list_cpp-vector示例,我们掌握了pybind11最基础也最重要的数据转换功能。这一简单却强大的特性,为Python与C++混合编程打开了大门,让开发者能够轻松构建高性能的应用程序。后续我们还将探索更多复杂数据结构的转换技巧,敬请关注!
【免费下载链接】pybind11_examplesExamples for the usage of "pybind11"项目地址: https://gitcode.com/gh_mirrors/py/pybind11_examples
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考