The Python function passes a reference to itself as the first argument, followed by real arguments given to the function. The PyArg_ParseTuple
function is used to parse values from the Python function to local variables in the C function. In this function, we cast a value to a double, and hence we use d
as the second argument. You can see a full list of strings that are accepted by this function at
https://docs.python.org/2/c-api/arg.html
.
The final result of the computations is returned using Py_Buildvalue
, which takes a similar type of format string to create a Python value from your answer. We use f
here, which stands for float, to demonstrate that double and float are treated similarly:
/* Implementation of the actual C funtions */ static PyObject* square_func(PyObject* self, PyObject* args) { double value; double answer; /* parse the input, from python float to c double */ if (!PyArg_ParseTuple(args, "d", &value)) return NULL; /* if the above function returns -1, an appropriate Python exception will * have been set, and the function simply returns NULL */ answer = value*value; return Py_BuildValue("f", answer); }
18.188.190.175