简体   繁体   中英

passing C++ string to Python

How could I pass a string from C++ to my Python function? I would like to get the string in my C++ application and parse it in Python

Initialize all required variables first.

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

Run a code to create a variable and set an initial value and print it inside python.

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

read the same variable from c++.

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

Above dictionary object is like a shared map. you can set a variable from c++. Then check the new value from python.

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

Have fun coding. Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM