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).
This commit is contained in:
Jason Rhinelander 2017-04-28 08:57:13 -04:00 committed by Wenzel Jakob
parent 1f8a100d38
commit ce494d65de
1 changed files with 5 additions and 0 deletions

View File

@ -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);