'What is the correct way to pass 2D ndarrays to C extension and get the new one?
The task is to create a C extention for Python which will take a 2D ndarray from python program and then, after some math operation (written with C) return a new ndarray. Here I wrote an example of code that should work:
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int processing(inarr) {
printf("Start...");
/*Here is a place for some C function*/
return outarr;
}
static PyObject *proc(PyObject *self, PyObject *args) {
PyObject *argin = NULL, *argout = NULL;
PyObject *inarr = NULL, *outarr = NULL;
inarr = PyArray_FROM_OTF(argin, NPY_DOUBLE, NPY_IN_ARRAY);
outarr = processing(inarr);
if(!PyArg_ParseTuple(args, "O!:ss", &argin, &argout)) {
return NULL;
}
return PyLong_FromLong(outarr);
}
static PyMethodDef ProcMethods[] = {
{"proc", proc, METH_VARARGS, "Method description"},
{NULL,NULL,0,NULL}
};
static struct PyModuleDef procmodule =
{
PyModuleDef_HEAD_INIT,
"proc",
"Description of my module",
-1,
ProcMethods
};
PyMODINIT_FUNC PyInit_procmodule(void) {
return PyModule_Create(procmodule)
};
But there are some questions.
Should I use PyArg_ParseTuple before if statement?
Is the init function correct (are there some special way to initiate it for 2D tuples)?
Is this enough to treat an ndarray within C function as array[][] without writing a matrix from a cycle by elements?
Will it work from python (after creating a package of course) like
import proc
proc(array)
UPD: Added initialisation function
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
