Reputation: 3340
I'm practicing with making C function calls from python (2.7).
I've succeed the example which is outlined on https://docs.python.org/2/extending/extending.html
Now I'm adjusting this example to multiply 2 floats and return the result. I've implemented the following function in my c source file.
static PyObject *demo_multiply(PyObject *self, PyObject *args)
{
const float *command;
float x;
if (!PyArg_ParseTuple(args, "f", &command)) return NULL;
x = command[0] * command[1];
return Py_BuildValue("f", x);
}
And I'm calling this function in python as follows:
print(demo.multiply((2.0, 4.0))
Which results in the following output:
Traceback (most recent call last): File "main.py", line 12, in print(demo.multiply((2.0, 4.0))) TypeError: a float is required
Clearly there is some mistake in my implementation, however I can't figure out what it is as believe I've quite clearly followed documentation on docs.python.org. Can somebody please point out what I'm missing here?
Upvotes: 4
Views: 144
Reputation: 3340
Thanks to user user2357112 comments, I've solved the problem. I've posted the code here for people encountering a similar problem.
(C)
static PyObject *demo_multiply(PyObject *self, PyObject *args)
{
float y[2];
float x;
if (!PyArg_ParseTuple(args, "ff", &(y[0]), &(y[1]))) return NULL;
x = y[0] * y[1];
return Py_BuildValue("f", x);
}
(Python)
print(demo.multiply(2.0, 4.0))
Upvotes: 4