@@ -14,6 +14,29 @@ cdef extern from *:
14
14
object char_to_string(const char * data)
15
15
16
16
17
+ cdef extern from * :
18
+ """
19
+ #if PY_VERSION_HEX >= 0x03000000
20
+ #define PyBytes_AsStringAndSize(py_string, buffer, length) \
21
+ PyBytes_AsStringAndSize(py_string, buffer, length)
22
+
23
+ #define PyUnicode_AsUTF8AndSize(py_string, buffer, length) \
24
+ buffer = PyUnicode_AsUTF8AndSize(py_string, length)
25
+
26
+ #else
27
+ #define PyBytes_AsStringAndSize(py_string, buffer, length) \
28
+ PyString_AsStringAndSize(py_string, buffer, length)
29
+
30
+ #define PyUnicode_AsUTF8AndSize(py_string, buffer, length) \
31
+ do { \
32
+ buffer = PyUnicode_AS_DATA(py_string); \
33
+ *length = PyUnicode_GET_SIZE(py_string); \
34
+ } while(0)
35
+ #endif
36
+ """
37
+ void PyUnicode_AsUTF8AndSize(object py_string, const char * buffer , Py_ssize_t* length)
38
+ void PyBytes_AsStringAndSize(object py_string, char ** buffer , Py_ssize_t* length)
39
+
17
40
cdef extern from " Python.h" :
18
41
# Note: importing extern-style allows us to declare these as nogil
19
42
# functions, whereas `from cpython cimport` does not.
@@ -24,15 +47,6 @@ cdef extern from "Python.h":
24
47
bint PyComplex_Check(object obj) nogil
25
48
bint PyObject_TypeCheck(object obj, PyTypeObject* type ) nogil
26
49
27
- # Note that following functions can potentially raise an exception,
28
- # thus they cannot be declared 'nogil'. Also PyUnicode_AsUTF8AndSize() can
29
- # potentially allocate memory inside in unlikely case of when underlying
30
- # unicode object was stored as non-utf8 and utf8 wasn't requested before.
31
- bint PyBytes_AsStringAndSize(object obj, char ** buf,
32
- Py_ssize_t* length) except - 1
33
- const char * PyUnicode_AsUTF8AndSize(object obj,
34
- Py_ssize_t* length) except NULL
35
-
36
50
from numpy cimport int64_t, float64_t
37
51
38
52
cdef extern from " numpy/arrayobject.h" :
@@ -243,7 +257,7 @@ cdef inline bint is_nan(object val):
243
257
244
258
245
259
cdef inline const char * get_c_string_buf_and_size(object py_string,
246
- Py_ssize_t * length):
260
+ Py_ssize_t * length) except NULL :
247
261
"""
248
262
Extract internal char* buffer of unicode or bytes object `py_string` with
249
263
getting length of this internal buffer saved in `length`.
@@ -263,10 +277,10 @@ cdef inline const char* get_c_string_buf_and_size(object py_string,
263
277
buf : const char*
264
278
"""
265
279
cdef:
266
- const char * buf
280
+ const char * buf = NULL
267
281
268
282
if PyUnicode_Check(py_string):
269
- buf = PyUnicode_AsUTF8AndSize(py_string, length)
283
+ PyUnicode_AsUTF8AndSize(py_string, buf , length)
270
284
else :
271
285
PyBytes_AsStringAndSize(py_string, < char ** > & buf, length)
272
286
return buf
0 commit comments