前言
- Windows平台,在实际C++项目开发中,结合pybind11库,让python成为C++的脚本语言,可以大大提高C++程序的可扩展性,大大提高开发效率,特别是针对多变的业务逻辑的优秀构架.
一、pybind11与Python环境配置
- pybind11安装
从GitHub上下载源码:https://github.com/pybind/pybind11 - 安装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完整源码
- vs2019 Csdn地址:https://download.csdn.net/download/qiangpi6057/87380952
分类:
python
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源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 设备加载的步骤及无法加载的解决办法