| 433 | |
| 434 | |
| 435 | std::string |
| 436 | PyStringToStdString(PyObject* py_val) |
| 437 | { |
| 438 | ///Must be locked |
| 439 | assert( PyThreadState_Get() ); |
| 440 | std::string val; |
| 441 | PyObject* s = nullptr; |
| 442 | // The following should work with Python 2 and 3. |
| 443 | // https://stackoverflow.com/a/38600095 |
| 444 | if (!py_val) { |
| 445 | val = "(null)"; |
| 446 | } else if( PyUnicode_Check(py_val) ) { // python3 has unicode, but we convert to bytes |
| 447 | s = PyUnicode_AsUTF8String(py_val); |
| 448 | } else if( PyBytes_Check(py_val) ) { // python2 has bytes already |
| 449 | s = PyObject_Bytes(py_val); |
| 450 | } else { |
| 451 | // Not a string => Error, warning ... |
| 452 | val = "(not a string)"; |
| 453 | } |
| 454 | |
| 455 | // If succesfully converted to bytes, then convert to C++ string |
| 456 | if (s) { |
| 457 | val = std::string( PyBytes_AS_STRING(s) ); |
| 458 | Py_XDECREF(s); |
| 459 | } |
| 460 | |
| 461 | return val; |
| 462 | } |
| 463 | |
| 464 | NATRON_PYTHON_NAMESPACE_EXIT |
| 465 |
no outgoing calls
no test coverage detected