前言
- 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