0

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

6
  • 1
    Check out boost::python Commented Aug 16, 2011 at 16:23
  • Or read the docs in the C API section. Commented 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. Commented Aug 16, 2011 at 16:45
  • 1
    The 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. Commented 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. Commented Aug 16, 2011 at 22:46

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.