[Numpy-discussion] c api, ndarray creation

Robert Kern robert.kern at gmail.com
Tue Nov 5 13:22:37 EST 2013


On Tue, Nov 5, 2013 at 6:10 PM, Sergey Petrov <qweqwegod at yahoo.com> wrote:
>
> Rather stupid question here, but I can't figure out by myself:
> Why does the following c program segfaults? And how can I avoid it?
>
> #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
>
> #include <Python.h>
> #include <numpy/arrayobject.h>
>
> int main(int argc, char *argv[])
> {
>    int nd=1;
>    npy_intp dims[] = {3};
>    npy_intp data[] = {1,2,3};
>    PyObject* array = PyArray_SimpleNewFromData(nd, dims, NPY_INT, (void*)
> data);
>    return 0;
> }

numpy is not a C library. It is a Python extension module. You can use its
C API from other Python extension modules, not C main programs. You have
not started a Python interpreter or imported the numpy module. Only then
will the numpy API be available.

Mechanically speaking, the proximate cause of your segfault is that
`PyArray_SimpleNewFromData` is not actually a function, but a macro that
looks up a function pointer from a static table defined in the numpy
module. Calling the macro `import_array()` will import the numpy module set
up this table with the correct function pointers. But you first need a
Python interpreter running.

--
Robert Kern
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20131105/778e5e68/attachment.html>


More information about the NumPy-Discussion mailing list