arraytest.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #include "Python.h"
  2. #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
  3. #include <math.h>
  4. #include "numpy/arrayobject.h"
  5. static PyObject* vecsq(PyObject* self, PyObject* args);
  6. static PyMethodDef arraytestMethods[] = { { "vecsq", vecsq, METH_VARARGS },
  7. { NULL, NULL } };
  8. static PyObject* vecsq(PyObject* self, PyObject* args)
  9. {
  10. PyArrayObject *vecin, *vecout;
  11. npy_intp dims[2];
  12. double *cin, *cout;
  13. int i, j, n, m;
  14. if (!PyArg_ParseTuple(args, "O!", &PyArray_Type, &vecin))
  15. return NULL;
  16. n = dims[0] = PyArray_NDIM(vecin);
  17. vecout = (PyArrayObject*)PyArray_SimpleNew(1, dims, NPY_DOUBLE);
  18. cin = (double*)PyArray_DATA(vecin);
  19. cout = (double*)PyArray_DATA(vecout);
  20. for (i = 0; i < n; i++) {
  21. cout[i] = cin[i] * cin[i];
  22. }
  23. return PyArray_Return(vecout);
  24. }
  25. #if defined(PYTHON2)
  26. PyMODINIT_FUNC initarraytest2(void)
  27. {
  28. (void)Py_InitModule("arraytest2", arraytestMethods);
  29. import_array();
  30. }
  31. #endif
  32. #if defined(PYTHON3)
  33. static struct PyModuleDef arraytestmodule = {
  34. PyModuleDef_HEAD_INIT, "arraytest3", /* name of module */
  35. NULL, /* module documentation, may be NULL */
  36. -1, /* size of per-interpreter state of the module,
  37. or -1 if the module keeps state in global variables. */
  38. arraytestMethods
  39. };
  40. PyMODINIT_FUNC PyInit_arraytest3(void)
  41. {
  42. PyObject* po = PyModule_Create(&arraytestmodule);
  43. import_array();
  44. return po;
  45. }
  46. #endif