使用Pybind11和CMake实现C++调用Python的配置求助
解决方案
1. 完善C++主程序代码
修改main.cpp,添加Pybind11调用Python函数的核心逻辑,包括初始化解释器、导入脚本模块、完成C++向量到Python列表的自动转换:
#include <vector> #include <pybind11/embed.h> #include <pybind11/stl.h> namespace py = pybind11; int main() { // 初始化Python解释器,作用域结束后自动清理 py::scoped_interpreter guard{}; // 获取sys模块,将当前目录添加到Python模块搜索路径 py::module_ sys = py::module_::import("sys"); sys.attr("path").attr("append")("."); // 导入自定义的python.py脚本模块 py::module_ py_module = py::module_::import("python"); // 构造测试用的向量(可替换为你的业务数据) std::vector<double> vec1 = {1.0, 2.0, 3.0}; std::vector<double> vec2 = {4.0, 5.0, 6.0}; // 调用Python函数,Pybind11自动完成std::vector到Python list的类型转换 py_module.attr("python_function")(vec1, vec2); return 0; }
2. 编写CMake配置文件
创建CMakeLists.txt,完成依赖查找、编译目标配置和库链接:
cmake_minimum_required(VERSION 3.16) project(cpp_call_python) # 查找全局安装的Pybind11 find_package(pybind11 REQUIRED) # 显式查找Python开发依赖(确保版本匹配) find_package(Python3 REQUIRED COMPONENTS Interpreter Development) # 添加可执行文件目标 add_executable(cpp_call_python main.cpp) # 链接Pybind11嵌入库和Python库 target_link_libraries(cpp_call_python PRIVATE pybind11::embed Python3::Python) # 指定C++编译标准(根据你的项目需求调整) target_compile_features(cpp_call_python PRIVATE cxx_std_17)
3. 关键注意事项
- Python脚本路径:C++代码中通过
sys.path.append(".")将当前工作目录加入搜索路径,运行程序时需确保python.py与可执行文件在同一目录;若脚本在其他路径,将.替换为对应绝对路径即可。 - Pybind11路径问题:如果
find_package(pybind11 REQUIRED)失败,可手动指定Pybind11的CMake配置路径,编译时添加参数:cmake .. -DPYBIND11_DIR=/path/to/pybind11/install/share/cmake/pybind11 - 版本匹配:确保编译时使用的Python版本与运行
python.py的版本一致,避免因版本差异导致的兼容性问题。
编译运行步骤
- 创建并进入构建目录:
mkdir build && cd build
- 生成构建文件:
cmake ..
- 编译项目:
make
- 运行可执行文件(确保
python.py在当前目录):
./cpp_call_python
内容的提问来源于stack exchange,提问作者intrigued_66
相关产品推荐
相关产品推荐

