如何将字符串从 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);
上面的字典对象就像一个共享 map 。你可以从 C++ 中设置一个变量。 然后从 python 检查新值。
dictionary["resultStr"] = "new value";//set the variable value
PyRun_SimpleString("print resultStr");//new value will reflect in python
享受编码乐趣。 谢谢。
关于c++ - 将 C++ 字符串传递给 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7081472/