将C++字符串传递给Python
我该如何把一个字符串从C++传递到我的Python函数呢?我想在我的C++应用程序中获取这个字符串,然后在Python中进行解析。
1 个回答
2
首先,先初始化所有需要的变量。
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
祝你编程愉快!谢谢。