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
-
1Check out boost::pythonGWW– GWW2011-08-16 16:23:35 +00:00Commented Aug 16, 2011 at 16:23
-
Or read the docs in the C API section.Seth Carnegie– Seth Carnegie2011-08-16 16:24:29 +00:00Commented Aug 16, 2011 at 16:24
-
Some clarification on what I'm trying to do: I have a float var in C++ that I would like to pass to a Python function that takes a float as a parameter. However, print statements in Python for the variable are outputting gibberish--I suspect that floats have different bits of precision? In C++ there are 7 bits after the decimal point, in Python, 6. So I want to convert the float to a string in C++, pass that to Python, truncate the number after the 6th decimal point, and convert it back to a float.jyoung– jyoung2011-08-16 16:45:57 +00:00Commented Aug 16, 2011 at 16:45
-
1The precision bits is a non-issue here. Python uses the same internal representation as C, because the interpreter is written in C. Anyway, PyFloat_FromDouble() should work. If not, you are doing something wrong, and the question should be about that, preferably with some code.rodrigo– rodrigo2011-08-16 21:12:26 +00:00Commented Aug 16, 2011 at 21:12
-
If you just want to pass a float between Python and C++, the quickest way to do it is to pass it via a file, especially if performance doesn't matter too much.Chinmay Kanchi– Chinmay Kanchi2011-08-16 22:46:56 +00:00Commented Aug 16, 2011 at 22:46
|
Show 1 more comment
1 Answer
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.