Search code examples
pythonc++boost

returning a variable string in Py_BuildValue


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


Solution

  • [Python.Docs]: Parsing arguments and building values - PyObject *Py_BuildValue(const char *format, ...) (or any other Python / C API function) works with C (not C++) types.

    In order to fix the problem, use [CPPReference]: std::basic_string<CharT,Traits,Allocator>::c_str:

    PyObject *python_val = Py_BuildValue("s", s.c_str());