From ce494d65de445bdfbf397f71ce0979e6e1dc249e Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Fri, 28 Apr 2017 08:57:13 -0400 Subject: [PATCH] Add numpy version check (#819) The numpy API constants can check past the end of the API array if the numpy version is too old thus causing a segfault. The current list of functions requires numpy >= 1.7.0, so this adds a check and exception if numpy is too old. The added feature version API element was added in numpy 1.4.0, so this could still segfault if loaded in 1.3.0 or earlier, but given that 1.4.0 was released at the end of 2009, it seems reasonable enough to not worry about that case. (1.7.0 was released in early 2013). --- include/pybind11/numpy.h | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/include/pybind11/numpy.h b/include/pybind11/numpy.h index b32c3887..cbf4c2f9 100644 --- a/include/pybind11/numpy.h +++ b/include/pybind11/numpy.h @@ -141,6 +141,7 @@ struct npy_api { return (bool) PyObject_TypeCheck(obj, PyArrayDescr_Type_); } + unsigned int (*PyArray_GetNDArrayCFeatureVersion_)(); PyObject *(*PyArray_DescrFromType_)(int); PyObject *(*PyArray_NewFromDescr_) (PyTypeObject *, PyObject *, int, Py_intptr_t *, @@ -160,6 +161,7 @@ struct npy_api { int (*PyArray_SetBaseObject_)(PyObject *, PyObject *); private: enum functions { + API_PyArray_GetNDArrayCFeatureVersion = 211, API_PyArray_Type = 2, API_PyArrayDescr_Type = 3, API_PyVoidArrType_Type = 39, @@ -186,6 +188,9 @@ private: #endif npy_api api; #define DECL_NPY_API(Func) api.Func##_ = (decltype(api.Func##_)) api_ptr[API_##Func]; + DECL_NPY_API(PyArray_GetNDArrayCFeatureVersion); + if (api.PyArray_GetNDArrayCFeatureVersion_() < 0x7) + pybind11_fail("pybind11 numpy support requires numpy >= 1.7.0"); DECL_NPY_API(PyArray_Type); DECL_NPY_API(PyVoidArrType_Type); DECL_NPY_API(PyArrayDescr_Type);