DoubleLi

qq: 517712484 wx: ldbgliet

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  4737 随笔 :: 2 文章 :: 542 评论 :: 1615万 阅读
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

 

 


前言

  • 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完整源码

 
posted on   DoubleLi  阅读(1179)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2021-11-16 linux C/C++中调用shell命令和运行shell脚本
2021-11-16 C++执行shell命令-linux
2021-11-16 C++中的STL中map用法详解
2021-11-16 C++中string append函数的使用与字符串拼接
2016-11-16 Linux下Wi-Fi的实现:wireless_tools和wpa_supplicant
2016-11-16 linux 无线网络配置工具wpa_supplicant与wireless-tools
2016-11-16 VirtualBox 下USB 设备加载的步骤及无法加载的解决办法
点击右上角即可分享
微信分享提示