returning a variable string in Py_BuildValue
Matthew Barrera
I'm writing the following as a test case in C++:
using namespace boost::algorithm;
static PyObject* strtest(PyObject* self, PyObject* args)
{ std::string s = "Boost C++ Libraries"; to_upper(s); PyObject * python_val = Py_BuildValue("s", s); return python_val;
}The code compiles and imports, but produces what looks like a reference to a memory location.
>>> math_demo.strtest()
' X\x0e'I was expecting 'BOOST C++ LIBRARIES' as a return value
What am I missing?
Thanks
21 Answer
[Python 3.Docs]: Parsing arguments and building values - PyObject* Py_BuildValue(const char *format, ...) (or any other Python / C API function) works with C types not C++.
In order to fix the problem, use [cplusplus]: std::string::c_str:
PyObject *python_val = Py_BuildValue("s", s.c_str()); 0