1. Antonio Cuni
  2. numpypy_c

Commits

Antonio Cuni  committed 9b5817f

shuffle things around and make numpypy_c a package

  • Participants
  • Parent commits ba61ae4
  • Branches default

Comments (0)

Files changed (14)

File c_test.c

-#include <Python.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <assert.h>
-
-#ifdef PYPY_VERSION
-#    include "numpypy_c.h"
-#else
-#    include <numpy/arrayobject.h>
-#endif
-
-#define py_assert(e) {                                                  \
-        if (!(e)) {                                                     \
-            PyErr_Format(PyExc_AssertionError, "%s:%u %s",              \
-                         __FILE__, __LINE__, #e);                       \
-            return NULL;                                                \
-        }                                                               \
-    }
-
-static PyObject*
-_frombuffer_2_2(PyObject *self, PyObject *args)
-{
-    npy_intp dims[2] = {2, 2};
-    long address;
-
-    if (!PyArg_ParseTuple(args, "l", &address))
-        return NULL;
-    void* data = (void*)address;
-
-    PyObject* obj = PyArray_SimpleNewFromData(2, dims, PyArray_FLOAT64, data);
-    return obj;
-}
-
-
-static PyObject*
-_test_DIMS(PyObject* self, PyObject* args) {
-    double data[4] = {1, 2, 3, 4};
-    npy_intp dims[2] = {2, 2};
-    PyObject* array = PyArray_SimpleNewFromData(2, dims, PyArray_FLOAT64, data);
-    //
-    py_assert(PyArray_NDIM(array) == 2);
-    npy_intp* dims2 = PyArray_DIMS(array);
-    py_assert(dims2[0] == 2);
-    py_assert(dims2[1] == 2);
-    Py_XDECREF(array);
-    Py_RETURN_NONE;
-}
-
-static PyObject*
-_test_Return(PyObject* self, PyObject* args) {
-    double data[4] = {1, 2, 3, 4};
-    npy_intp dims[2] = {2, 2};
-    PyObject* array = PyArray_SimpleNewFromData(2, dims, PyArray_FLOAT64, data);
-    py_assert(PyArray_Return((PyArrayObject*)array) == array);
-    Py_XDECREF(array);
-    Py_RETURN_NONE;
-}
-
-static PyObject*
-_test_DATA(PyObject* self, PyObject* args) {
-    double data[4] = {1, 2, 3, 4};
-    npy_intp dims[2] = {2, 2};
-    PyObject* array = PyArray_SimpleNewFromData(2, dims, PyArray_FLOAT64, data);
-    void* data2 = PyArray_DATA(array);
-    py_assert(data2 == (void*)(data));
-    Py_XDECREF(array);
-    Py_RETURN_NONE;
-}
-
-static PyObject*
-_test_STRIDES(PyObject* self, PyObject* args) {
-    double* data = (double*)0x01; // a non-NULL pointer
-    npy_intp dims[3] = {3, 5, 7};
-    PyObject* array = PyArray_SimpleNewFromData(3, dims, PyArray_FLOAT64, data);
-    npy_intp* strides = PyArray_STRIDES(array);
-    py_assert(strides[0] == 7*5*sizeof(double));
-    py_assert(strides[1] == 7*sizeof(double));
-    py_assert(strides[2] == sizeof(double));
-    Py_XDECREF(array);
-
-    npy_intp dims2[2] = {4, 2};
-    array = PyArray_SimpleNewFromData(2, dims2, PyArray_FLOAT64, NULL);
-    strides = PyArray_STRIDES(array);
-    py_assert(strides[0] == sizeof(double));
-    py_assert(strides[1] == 4*sizeof(double));
-    Py_XDECREF(array);
-    Py_RETURN_NONE;
-}
-
-
-static PyMethodDef c_test_methods[] = {
-    {"_frombuffer_2_2", _frombuffer_2_2, METH_VARARGS, "..."},
-    {"_test_DIMS", _test_DIMS, METH_NOARGS, "..."},
-    {"_test_Return", _test_Return, METH_NOARGS, "..."},
-    {"_test_DATA", _test_DATA, METH_NOARGS, "..."},
-    /* {"_test_STRIDES", _test_STRIDES, METH_NOARGS, "..."}, */
-    {NULL}  /* Sentinel */
-};
-
-#ifndef PyMODINIT_FUNC	/* declarations for DLL import/export */
-#define PyMODINIT_FUNC void
-#endif
-PyMODINIT_FUNC
-initc_test(void) 
-{
-    PyObject* m;
-
-    m = Py_InitModule3("c_test", c_test_methods,
-                       "C tests for numpypy_c");
-    import_array();
-}

File conftest.py

View file
         raise KeyboardInterrupt
     plat_dir = "lib.%s-%s" % (get_platform(), sys.version[0:3])
     build_dir = BUILD.join(plat_dir)
-    for so in build_dir.listdir('*.so'):
-        so.copy(ROOT)
+    for so in build_dir.visit('*.so'):
+        relname = so.relto(build_dir)
+        so.copy(ROOT.join(relname))

File cpyext_bridge.c

-#include <Python.h>
-
-static PyObject*
-to_C(PyObject* self, PyObject* args) {
-    PyObject* obj;
-    if (!PyArg_ParseTuple(args, "O", &obj))
-        return NULL;
-    Py_INCREF(obj);
-    return Py_BuildValue("l", (Py_ssize_t)obj);
-}
-
-static PyObject*
-from_C(PyObject* self, PyObject* args) {
-    Py_ssize_t addr;
-    if (!PyArg_ParseTuple(args, "n", &addr))
-        return NULL;
-    PyObject* obj = (PyObject*)addr;
-    Py_INCREF(obj); // XXX: we should think of a way to free it
-    return obj;
-}
-
-static PyMethodDef methods[] = {
-    {"to_C", to_C, METH_VARARGS, "..."},
-    {"from_C", from_C, METH_VARARGS, "..."},
-    {NULL}  /* Sentinel */
-};
-
-#ifndef PyMODINIT_FUNC	/* declarations for DLL import/export */
-#define PyMODINIT_FUNC void
-#endif
-PyMODINIT_FUNC
-initcpyext_bridge(void) 
-{
-    PyObject* m;
-    m = Py_InitModule3("cpyext_bridge", methods, "cpyext bridge");
-}

File include/numpypy_c.h

View file
+#ifndef NUMPYPY_C_H
+#define NUMPYPY_C_H
+#include <Python.h>
+
+enum NPY_TYPES {    NPY_BOOL=0,
+                    NPY_BYTE, NPY_UBYTE,
+                    NPY_SHORT, NPY_USHORT,
+                    NPY_INT, NPY_UINT,
+                    NPY_LONG, NPY_ULONG,
+                    NPY_LONGLONG, NPY_ULONGLONG,
+                    NPY_FLOAT, NPY_DOUBLE, NPY_LONGDOUBLE,
+                    NPY_CFLOAT, NPY_CDOUBLE, NPY_CLONGDOUBLE,
+                    NPY_OBJECT=17,
+                    NPY_STRING, NPY_UNICODE,
+                    NPY_VOID,
+                    /*
+                     * New 1.6 types appended, may be integrated
+                     * into the above in 2.0.
+                     */
+                    NPY_DATETIME, NPY_TIMEDELTA, NPY_HALF,
+
+                    NPY_NTYPES,
+                    NPY_NOTYPE,
+                    NPY_CHAR,      /* special flag */
+                    NPY_USERDEF=256,  /* leave room for characters */
+
+                    /* The number of types not including the new 1.6 types */
+                    NPY_NTYPES_ABI_COMPATIBLE=21
+};
+
+#define PyArray_FLOAT64 NPY_DOUBLE
+typedef long npy_intp;
+typedef struct _PyArrayObject PyArrayObject;
+
+static void* get_ptr(PyObject* impl, PyObject* ffi, const char* name) {
+    PyObject* callback = PyObject_GetAttrString(impl, name);
+    if (!callback)
+        return NULL;
+    
+    PyObject* addr_obj = PyObject_CallMethod(ffi, "cast", "(sO)", "long", callback);
+    if (!addr_obj)
+        return NULL;
+
+    addr_obj = PyNumber_Int(addr_obj);
+    if (!addr_obj)
+        return NULL;
+
+    long addr = PyInt_AsLong(addr_obj);
+    if (addr == -1 && PyErr_Occurred())
+        return NULL;
+
+    return (void*)addr;
+}
+
+#define IMPORT(name) {                          \
+    name = get_ptr(impl, ffi, #name);           \
+    if (!name)                                  \
+        return -1;                              \
+    }
+
+static PyObject* (*PyArray_SimpleNewFromData)(int nd, npy_intp* dims,  int typenum, void* data);
+
+static int (*PyArray_NDIM)(PyObject* array);
+static npy_intp* (*PyArray_DIMS)(PyObject* array);
+static PyObject* (*PyArray_Return)(PyArrayObject* array);
+static void* (*PyArray_DATA)(PyObject* array);
+static npy_intp* (*PyArray_STRIDES)(PyObject* array);
+
+static int 
+import_array(void) {
+    PyObject* impl = PyImport_ImportModule("numpypy_c.impl");
+    if (!impl)
+        return -1;
+
+    PyObject* ffi = PyObject_GetAttrString(impl, "ffi");
+    if (!ffi)
+        return -1;
+
+    IMPORT(PyArray_SimpleNewFromData);
+    IMPORT(PyArray_DIMS);
+    IMPORT(PyArray_NDIM);
+    IMPORT(PyArray_Return);
+    IMPORT(PyArray_DATA);
+    IMPORT(PyArray_STRIDES);
+}
+
+#endif

File numpypy_c.h

-#ifndef NUMPYPY_C_H
-#define NUMPYPY_C_H
-#include <Python.h>
-
-enum NPY_TYPES {    NPY_BOOL=0,
-                    NPY_BYTE, NPY_UBYTE,
-                    NPY_SHORT, NPY_USHORT,
-                    NPY_INT, NPY_UINT,
-                    NPY_LONG, NPY_ULONG,
-                    NPY_LONGLONG, NPY_ULONGLONG,
-                    NPY_FLOAT, NPY_DOUBLE, NPY_LONGDOUBLE,
-                    NPY_CFLOAT, NPY_CDOUBLE, NPY_CLONGDOUBLE,
-                    NPY_OBJECT=17,
-                    NPY_STRING, NPY_UNICODE,
-                    NPY_VOID,
-                    /*
-                     * New 1.6 types appended, may be integrated
-                     * into the above in 2.0.
-                     */
-                    NPY_DATETIME, NPY_TIMEDELTA, NPY_HALF,
-
-                    NPY_NTYPES,
-                    NPY_NOTYPE,
-                    NPY_CHAR,      /* special flag */
-                    NPY_USERDEF=256,  /* leave room for characters */
-
-                    /* The number of types not including the new 1.6 types */
-                    NPY_NTYPES_ABI_COMPATIBLE=21
-};
-
-#define PyArray_FLOAT64 NPY_DOUBLE
-typedef long npy_intp;
-typedef struct _PyArrayObject PyArrayObject;
-
-static void* get_ptr(PyObject* impl, PyObject* ffi, const char* name) {
-    PyObject* callback = PyObject_GetAttrString(impl, name);
-    if (!callback)
-        return NULL;
-    
-    PyObject* addr_obj = PyObject_CallMethod(ffi, "cast", "(sO)", "long", callback);
-    if (!addr_obj)
-        return NULL;
-
-    addr_obj = PyNumber_Int(addr_obj);
-    if (!addr_obj)
-        return NULL;
-
-    long addr = PyInt_AsLong(addr_obj);
-    if (addr == -1 && PyErr_Occurred())
-        return NULL;
-
-    return (void*)addr;
-}
-
-#define IMPORT(name) {                          \
-    name = get_ptr(impl, ffi, #name);           \
-    if (!name)                                  \
-        return -1;                              \
-    }
-
-static PyObject* (*PyArray_SimpleNewFromData)(int nd, npy_intp* dims,  int typenum, void* data);
-
-static int (*PyArray_NDIM)(PyObject* array);
-static npy_intp* (*PyArray_DIMS)(PyObject* array);
-static PyObject* (*PyArray_Return)(PyArrayObject* array);
-static void* (*PyArray_DATA)(PyObject* array);
-static npy_intp* (*PyArray_STRIDES)(PyObject* array);
-
-static int 
-import_array(void) {
-    PyObject* impl = PyImport_ImportModule("numpypy_c");
-    if (!impl)
-        return -1;
-
-    PyObject* ffi = PyObject_GetAttrString(impl, "ffi");
-    if (!ffi)
-        return -1;
-
-    IMPORT(PyArray_SimpleNewFromData);
-    IMPORT(PyArray_DIMS);
-    IMPORT(PyArray_NDIM);
-    IMPORT(PyArray_Return);
-    IMPORT(PyArray_DATA);
-    IMPORT(PyArray_STRIDES);
-}
-
-#endif

File numpypy_c.py

-import cffi
-import cpyext_bridge
-import numpypy as np
-
-ffi = cffi.FFI()
-
-ffi.cdef("""
-typedef long npy_intp;
-typedef struct _object PyObject;
-""")
-
-def to_C(obj):
-    addr = cpyext_bridge.to_C(obj)
-    return ffi.cast("PyObject*", addr)
-
-def from_C(ptr):
-    addr = ffi.cast("ssize_t", ptr)
-    return cpyext_bridge.from_C(addr)
-
-def build_typenum():
-    d = {}
-    for info in np.typeinfo.itervalues():
-        if isinstance(info, tuple):
-            dtype = info[-1]
-            d[info[1]] = dtype
-    typenum = [dtype for _, dtype in sorted(d.items())]
-    return typenum
-
-TYPENUM = build_typenum()
-
-class ExtraData(object):
-    def __init__(self, array):
-        ndim = len(array.shape)
-        self.dims = ffi.new("npy_intp[]", ndim)
-        for i, dim in enumerate(array.shape):
-            self.dims[i] = dim
-
-    @classmethod
-    def get(cls, array):
-        data = array.__pypy_data__
-        if not data:
-            data = array.__pypy_data__ = cls(array)
-        return data
-
-@ffi.callback("PyObject*(int, npy_intp*, int, void*)")
-def PyArray_SimpleNewFromData(nd, dims, typenum, data):
-    shape = [dims[i] for i in range(nd)]
-    dtype = TYPENUM[typenum]
-    data = ffi.cast("long", data)
-    array = np.ndarray._from_shape_and_storage(shape, data, dtype)
-    ExtraData.get(array)
-    addr = to_C(array)
-    return addr
-
-@ffi.callback("int(PyObject*)")
-def PyArray_NDIM(addr):
-    array = from_C(addr)
-    return len(array.shape)
-
-@ffi.callback("npy_intp*(PyObject*)")
-def PyArray_DIMS(addr):
-    array = from_C(addr)
-    return ExtraData.get(array).dims
-
-@ffi.callback("PyObject*(PyObject*)")
-def PyArray_Return(addr):
-    array = from_C(addr)
-    assert len(array.shape) > 0 # I don't really understood what it's supposed
-                                # to happen for 0-dimensional arrays :)
-    return addr
-
-@ffi.callback("void*(PyObject*)")
-def PyArray_DATA(addr):
-    array = from_C(addr)
-    data, _ = array.__array_interface__['data']
-    return ffi.cast("void*", data)
-
-@ffi.callback("npy_intp*(PyObject*)")
-def PyArray_STRIDES(addr):
-    array = from_C(addr)
-    import pdb;pdb.set_trace()

File numpypy_c/__init__.py

Empty file added.

File numpypy_c/cpyext_bridge.c

View file
+#include <Python.h>
+
+static PyObject*
+to_C(PyObject* self, PyObject* args) {
+    PyObject* obj;
+    if (!PyArg_ParseTuple(args, "O", &obj))
+        return NULL;
+    Py_INCREF(obj);
+    return Py_BuildValue("l", (Py_ssize_t)obj);
+}
+
+static PyObject*
+from_C(PyObject* self, PyObject* args) {
+    Py_ssize_t addr;
+    if (!PyArg_ParseTuple(args, "n", &addr))
+        return NULL;
+    PyObject* obj = (PyObject*)addr;
+    Py_INCREF(obj); // XXX: we should think of a way to free it
+    return obj;
+}
+
+static PyMethodDef methods[] = {
+    {"to_C", to_C, METH_VARARGS, "..."},
+    {"from_C", from_C, METH_VARARGS, "..."},
+    {NULL}  /* Sentinel */
+};
+
+#ifndef PyMODINIT_FUNC	/* declarations for DLL import/export */
+#define PyMODINIT_FUNC void
+#endif
+PyMODINIT_FUNC
+initcpyext_bridge(void) 
+{
+    PyObject* m;
+    m = Py_InitModule3("cpyext_bridge", methods, "cpyext bridge");
+}

File numpypy_c/impl.py

View file
+import cffi
+import cpyext_bridge
+import numpypy as np
+
+ffi = cffi.FFI()
+
+ffi.cdef("""
+typedef long npy_intp;
+typedef struct _object PyObject;
+""")
+
+def to_C(obj):
+    addr = cpyext_bridge.to_C(obj)
+    return ffi.cast("PyObject*", addr)
+
+def from_C(ptr):
+    addr = ffi.cast("ssize_t", ptr)
+    return cpyext_bridge.from_C(addr)
+
+def build_typenum():
+    d = {}
+    for info in np.typeinfo.itervalues():
+        if isinstance(info, tuple):
+            dtype = info[-1]
+            d[info[1]] = dtype
+    typenum = [dtype for _, dtype in sorted(d.items())]
+    return typenum
+
+TYPENUM = build_typenum()
+
+class ExtraData(object):
+    def __init__(self, array):
+        ndim = len(array.shape)
+        self.dims = ffi.new("npy_intp[]", ndim)
+        for i, dim in enumerate(array.shape):
+            self.dims[i] = dim
+
+    @classmethod
+    def get(cls, array):
+        data = array.__pypy_data__
+        if not data:
+            data = array.__pypy_data__ = cls(array)
+        return data
+
+@ffi.callback("PyObject*(int, npy_intp*, int, void*)")
+def PyArray_SimpleNewFromData(nd, dims, typenum, data):
+    shape = [dims[i] for i in range(nd)]
+    dtype = TYPENUM[typenum]
+    data = ffi.cast("long", data)
+    array = np.ndarray._from_shape_and_storage(shape, data, dtype)
+    ExtraData.get(array)
+    addr = to_C(array)
+    return addr
+
+@ffi.callback("int(PyObject*)")
+def PyArray_NDIM(addr):
+    array = from_C(addr)
+    return len(array.shape)
+
+@ffi.callback("npy_intp*(PyObject*)")
+def PyArray_DIMS(addr):
+    array = from_C(addr)
+    return ExtraData.get(array).dims
+
+@ffi.callback("PyObject*(PyObject*)")
+def PyArray_Return(addr):
+    array = from_C(addr)
+    assert len(array.shape) > 0 # I don't really understood what it's supposed
+                                # to happen for 0-dimensional arrays :)
+    return addr
+
+@ffi.callback("void*(PyObject*)")
+def PyArray_DATA(addr):
+    array = from_C(addr)
+    data, _ = array.__array_interface__['data']
+    return ffi.cast("void*", data)
+
+@ffi.callback("npy_intp*(PyObject*)")
+def PyArray_STRIDES(addr):
+    array = from_C(addr)
+    import pdb;pdb.set_trace()

File numpypy_c/testing/__init__.py

Empty file added.

File numpypy_c/testing/c_test.c

View file
+#include <Python.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <assert.h>
+
+#ifdef PYPY_VERSION
+#    include "numpypy_c.h"
+#else
+#    include <numpy/arrayobject.h>
+#endif
+
+#define py_assert(e) {                                                  \
+        if (!(e)) {                                                     \
+            PyErr_Format(PyExc_AssertionError, "%s:%u %s",              \
+                         __FILE__, __LINE__, #e);                       \
+            return NULL;                                                \
+        }                                                               \
+    }
+
+static PyObject*
+_frombuffer_2_2(PyObject *self, PyObject *args)
+{
+    npy_intp dims[2] = {2, 2};
+    long address;
+
+    if (!PyArg_ParseTuple(args, "l", &address))
+        return NULL;
+    void* data = (void*)address;
+
+    PyObject* obj = PyArray_SimpleNewFromData(2, dims, PyArray_FLOAT64, data);
+    return obj;
+}
+
+
+static PyObject*
+_test_DIMS(PyObject* self, PyObject* args) {
+    double data[4] = {1, 2, 3, 4};
+    npy_intp dims[2] = {2, 2};
+    PyObject* array = PyArray_SimpleNewFromData(2, dims, PyArray_FLOAT64, data);
+    //
+    py_assert(PyArray_NDIM(array) == 2);
+    npy_intp* dims2 = PyArray_DIMS(array);
+    py_assert(dims2[0] == 2);
+    py_assert(dims2[1] == 2);
+    Py_XDECREF(array);
+    Py_RETURN_NONE;
+}
+
+static PyObject*
+_test_Return(PyObject* self, PyObject* args) {
+    double data[4] = {1, 2, 3, 4};
+    npy_intp dims[2] = {2, 2};
+    PyObject* array = PyArray_SimpleNewFromData(2, dims, PyArray_FLOAT64, data);
+    py_assert(PyArray_Return((PyArrayObject*)array) == array);
+    Py_XDECREF(array);
+    Py_RETURN_NONE;
+}
+
+static PyObject*
+_test_DATA(PyObject* self, PyObject* args) {
+    double data[4] = {1, 2, 3, 4};
+    npy_intp dims[2] = {2, 2};
+    PyObject* array = PyArray_SimpleNewFromData(2, dims, PyArray_FLOAT64, data);
+    void* data2 = PyArray_DATA(array);
+    py_assert(data2 == (void*)(data));
+    Py_XDECREF(array);
+    Py_RETURN_NONE;
+}
+
+static PyObject*
+_test_STRIDES(PyObject* self, PyObject* args) {
+    double* data = (double*)0x01; // a non-NULL pointer
+    npy_intp dims[3] = {3, 5, 7};
+    PyObject* array = PyArray_SimpleNewFromData(3, dims, PyArray_FLOAT64, data);
+    npy_intp* strides = PyArray_STRIDES(array);
+    py_assert(strides[0] == 7*5*sizeof(double));
+    py_assert(strides[1] == 7*sizeof(double));
+    py_assert(strides[2] == sizeof(double));
+    Py_XDECREF(array);
+
+    npy_intp dims2[2] = {4, 2};
+    array = PyArray_SimpleNewFromData(2, dims2, PyArray_FLOAT64, NULL);
+    strides = PyArray_STRIDES(array);
+    py_assert(strides[0] == sizeof(double));
+    py_assert(strides[1] == 4*sizeof(double));
+    Py_XDECREF(array);
+    Py_RETURN_NONE;
+}
+
+
+static PyMethodDef c_test_methods[] = {
+    {"_frombuffer_2_2", _frombuffer_2_2, METH_VARARGS, "..."},
+    {"_test_DIMS", _test_DIMS, METH_NOARGS, "..."},
+    {"_test_Return", _test_Return, METH_NOARGS, "..."},
+    {"_test_DATA", _test_DATA, METH_NOARGS, "..."},
+    /* {"_test_STRIDES", _test_STRIDES, METH_NOARGS, "..."}, */
+    {NULL}  /* Sentinel */
+};
+
+#ifndef PyMODINIT_FUNC	/* declarations for DLL import/export */
+#define PyMODINIT_FUNC void
+#endif
+PyMODINIT_FUNC
+initc_test(void) 
+{
+    PyObject* m;
+
+    m = Py_InitModule3("c_test", c_test_methods,
+                       "C tests for numpypy_c");
+    import_array();
+}

File numpypy_c/testing/test_numpypy_c.py

View file
+import py
+import ctypes
+from numpypy_c.testing import c_test
+try:
+    import numpypy as np
+    is_pypy = True
+except ImportError:
+    import numpy as np
+    is_pypy = False
+
+def _import_c_tests(mod):
+    glob = globals()
+    for name, value in mod.__dict__.iteritems():
+        if name.startswith('_test'):
+            fn_name = name[1:]
+            def fn(test=value):
+                test()
+            fn.__name__ = fn_name
+            glob[fn_name] = fn
+
+_import_c_tests(c_test)
+
+
+def test_SimpleNewFromData():
+    buf = (ctypes.c_double*4)(1, 2, 3, 4)
+    addr = ctypes.cast(buf, ctypes.c_void_p).value
+    array = c_test._frombuffer_2_2(addr)
+    assert isinstance(array, np.ndarray)
+    assert array.dtype == np.float64
+    assert array[0, 0] == 1
+    assert array[0, 1] == 2
+    assert array[1, 0] == 3
+    assert array[1, 1] == 4
+    #
+    array[0, 0] = 42
+    assert buf[0] == 42
+

File setup.py

View file
 import sys
-is_pypy = hasattr(sys, 'pypy_version_info')
+import os
 from distutils.core import setup, Extension
 
-cpyext_bridge = Extension('cpyext_bridge',
-                          sources = ['cpyext_bridge.c'])
+ROOT = os.path.dirname(__file__)
+INCLUDE = os.path.join(ROOT, 'include')
 
-c_test = Extension('c_test',
-                           sources = ['c_test.c'],
-                           depends = ['numpypy_c.h'],
-                           extra_compile_args=['-g'])
+cpyext_bridge = Extension('numpypy_c.cpyext_bridge',
+                          sources = ['numpypy_c/cpyext_bridge.c'])
+
+c_test = Extension('numpypy_c.testing.c_test',
+                   sources = ['numpypy_c/testing/c_test.c'],
+                   depends = ['include/numpypy_c.h'],
+                   include_dirs = [INCLUDE])
 
 ext_modules = [cpyext_bridge, c_test]
 

File test_numpypy_c.py

-import py
-import ctypes
-import c_test
-try:
-    import numpypy as np
-    is_pypy = True
-except ImportError:
-    import numpy as np
-    is_pypy = False
-
-def _import_c_tests(mod):
-    glob = globals()
-    for name, value in mod.__dict__.iteritems():
-        if name.startswith('_test'):
-            fn_name = name[1:]
-            def fn(test=value):
-                test()
-            fn.__name__ = fn_name
-            glob[fn_name] = fn
-
-_import_c_tests(c_test)
-
-
-def test_SimpleNewFromData():
-    buf = (ctypes.c_double*4)(1, 2, 3, 4)
-    addr = ctypes.cast(buf, ctypes.c_void_p).value
-    array = c_test._frombuffer_2_2(addr)
-    assert isinstance(array, np.ndarray)
-    assert array.dtype == np.float64
-    assert array[0, 0] == 1
-    assert array[0, 1] == 2
-    assert array[1, 0] == 3
-    assert array[1, 1] == 4
-    #
-    array[0, 0] = 42
-    assert buf[0] == 42
-