Returning a Variable String in Py_Buildvalue

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

2

1 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

Your Answer

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

Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.