1 /* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
2
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15
16 #include "tensorflow/lite/python/interpreter_wrapper/python_utils.h"
17
18 #include <memory>
19
20 namespace tflite {
21 namespace python_utils {
22
ConvertFromPyString(PyObject * obj,char ** data,Py_ssize_t * length)23 int ConvertFromPyString(PyObject* obj, char** data, Py_ssize_t* length) {
24 #if PY_MAJOR_VERSION >= 3
25 if (PyUnicode_Check(obj)) {
26 // const_cast<> is for CPython 3.7 finally adding const to the API.
27 *data = const_cast<char*>(PyUnicode_AsUTF8AndSize(obj, length));
28 return *data == nullptr ? -1 : 0;
29 }
30 return PyBytes_AsStringAndSize(obj, data, length);
31 #else
32 return PyString_AsStringAndSize(obj, data, length);
33 #endif
34 }
35
ConvertToPyString(const char * data,size_t length)36 PyObject* ConvertToPyString(const char* data, size_t length) {
37 #if PY_MAJOR_VERSION >= 3
38 return PyBytes_FromStringAndSize(data, length);
39 #else
40 return PyString_FromStringAndSize(data, length);
41 #endif
42 }
43
44 } // namespace python_utils
45 } // namespace tflite
46