Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract a python str with C API, compatible with python 2&3

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?

like image 580
fffred Avatar asked Oct 14 '25 22:10

fffred


1 Answers

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);
}
like image 64
fffred Avatar answered Oct 17 '25 12:10

fffred



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!