4

My c++ code runs a python interpreter to read an external python file, and I am trying to make the C API accept both python 2 and python 3 strings.

If python 2.7.11, I use PyString_Check and PyString_AsString.

If python 3.5.2, I use PyUnicode_Check and PyUnicode_AsUTF8String.

The former technique is deprecated in python 3.x.

I was expecting the latter to be compatible to both versions. However, PyUnicode_Check returns false under python 2 for an argument of type str. Furthermore, PyUnicode_AsUTF8String gives a segmentation fault in this case.

What am I doing wrong?

fffred
  • 596
  • 4
  • 19

1 Answers1

3

I finally found a way to extract a string from python versions 2.7 and 3.5 (at least)

PyObject *s;
if( PyUnicode_Check(py_val) ) {  // python3 has unicode, but we convert to bytes
    s = PyUnicode_AsUTF8String(py_val);
} else if( PyBytes_Check(py_val) ) {  // python2 has bytes already
    s = PyObject_Bytes(py_val);
} else {
    // Not a string => Error, warning ...
}

// If succesfully converted to bytes, then convert to C++ string
std::string val("");
if(s) {
    val = std::string( PyBytes_AsString(s) );
    Py_XDECREF(s);
}
fffred
  • 596
  • 4
  • 19