基于pybind11实现C++程序中调用Python脚本增加C++程序扩展性


前言

  • Windows平台,在实际C++项目开发中,结合pybind11库,让python成为C++的脚本语言,可以大大提高C++程序的可扩展性,大大提高开发效率,特别是针对多变的业务逻辑的优秀构架.

一、pybind11与Python环境配置

  1. pybind11安装
    从GitHub上下载源码:https://github.com/pybind/pybind11
  2. 安装Python3.7
    具体教程:https://blog.csdn.net/qq_40969467/article/details/82763878

二、C++环境配置

  • 下载visual studio2015之后的版本
    配置C++开发环境
    注: pybind11只支持visual studio2015之后的版本

  • 新建C++项目
    在这里插入图片描述

  • C++项目环境配置
    ---- 项目文件目录结构
    在这里插入图片描述
    ---- 项目属性配置
    在这里插入图片描述
    在这里插入图片描述在这里插入图片描述

三、C++调用Python交互代码

-----通过pybind11,c++可以很方便的调用python中的函数,并互传参数,
-----这里运行时注意pybind11默认会将C++编译的exe运行路径加入到python的工作目录中,默认情况下,python脚本只有放到C++的exe同级目录中,才会被加载到.
----为方便脚本文件的管理,可以用特殊方法处理:将整理py脚本的文件加动态加入到python的工作目录中:

import sys
import pathlib
import os
sys.path.append(os.path.join(pathlib.Path(file).parent.absolute(), ‘PythonScript’))

#include <iostream>
#include <pybind11/pybind11.h>
#include <pybind11/embed.h>
namespace py = pybind11;
using namespace std;

void InitPython()
{
    
    
    //用于指定脚本路径
	py::module asd = py::module::import("PythonScriptPathConf");
}

int main()
{
    
    
	/*py::scoped_interpreter guard{};
	py::module math = py::module::import("test");
	py::object result = math.attr("Add")("25");
	std::cout << "Sqrt of 25 is: " << result.cast<float>() << std::endl;
    std::cout << "Hello World!\n";*/
	py::scoped_interpreter python;
	py::module sys = py::module::import("sys");
	try
	{
    
    
		InitPython();
		py::print(sys.attr("path"));
		py::module t = py::module::import("test3");
		py::object result;
		//传递int
		result = t.attr("Add")(1);
		//传递string参数
		auto resultStr = t.attr("StrTest")("Str123");
		auto outArray = result.cast<int>();
		printf("outArray:%d\n", outArray);
		printf("Str:%s", resultStr.cast<string>());
	}
	catch (std::exception& e)
	{
    
    
		cout << "call python transpose failed:" << e.what() << endl;
	}
}

四、C++调用Python Demo完整源码

猜你喜欢

转载自blog.csdn.net/qiangpi6057/article/details/128656361