| 27 | |
| 28 | template<typename T> |
| 29 | T setstate(py::tuple state) |
| 30 | { |
| 31 | using namespace dlib; |
| 32 | if (len(state) != 1) |
| 33 | { |
| 34 | PyErr_SetObject(PyExc_ValueError, |
| 35 | py::str("expected 1-item tuple in call to __setstate__; got {}").format(state).ptr() |
| 36 | ); |
| 37 | throw py::error_already_set(); |
| 38 | } |
| 39 | |
| 40 | // We used to serialize by converting to a str but the boost.python routines for |
| 41 | // doing this don't work in Python 3. You end up getting an error about invalid |
| 42 | // UTF-8 encodings. So instead we access the python C interface directly and use |
| 43 | // bytes objects. However, we keep the deserialization code that worked with str |
| 44 | // for backwards compatibility with previously pickled files. |
| 45 | T item; |
| 46 | py::object obj = state[0]; |
| 47 | if (py::isinstance<py::str>(obj)) |
| 48 | { |
| 49 | py::str data = state[0].cast<py::str>(); |
| 50 | std::string temp = data; |
| 51 | std::istringstream sin(temp); |
| 52 | deserialize(item, sin); |
| 53 | } |
| 54 | else if(PyBytes_Check(py::object(state[0]).ptr())) |
| 55 | { |
| 56 | py::object obj = state[0]; |
| 57 | char* data = PyBytes_AsString(obj.ptr()); |
| 58 | unsigned long num = PyBytes_Size(obj.ptr()); |
| 59 | std::istringstream sin(std::string(data, num)); |
| 60 | deserialize(item, sin); |
| 61 | } |
| 62 | else |
| 63 | { |
| 64 | throw error("Unable to unpickle, error in input file."); |
| 65 | } |
| 66 | |
| 67 | return item; |
| 68 | } |
| 69 | |
| 70 | } |
| 71 | |