Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

returning a variable string in Py_BuildValue

Writer 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

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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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.