将c++字符串传递给Python

passing C++ string to Python

本文关键字:Python c++ 字符串      更新时间:2023-10-16

我怎么能传递一个字符串从c++到我的Python函数?我想在我的c++应用程序中获得字符串并在Python中解析它

先初始化所有需要的变量

Py_Initialize();
object  main_module = import("__main__");//boost::python objects
object  dictionary = main_module.attr("__dict__");

运行代码创建一个变量,设置一个初始值,并在python中打印。

boost::python::exec("resultStr = 'oldvalue'", dictionary);
PyRun_SimpleString("print resultStr");//new value will reflect in python

从c++中读取相同的变量

boost::python::object resultStr = dictionary["resultStr"];//read value from python to c++
std::string &processedScript = extract<std::string>(resultStr);

上面的字典对象类似于一个共享映射。您可以从c++中设置变量。然后检查python的新值。

dictionary["resultStr"] = "new value";//set the variable value
PyRun_SimpleString("print resultStr");//new value will reflect in python

玩得开心。谢谢。