I've recently started using the Python/C API to build modules for Python using C code. I've been trying to pass a Python list of numbers to a C function without success:
asdf_module.c
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <Python.h>
int _asdf(int low, int high, double *pr)
// ...
for (i = 0; i < range; i++)
{
printf("pr[%d] = %f\n", i, pr[i]);
}
// ...
return 0;
}
static PyObject*
asdf(PyObject* self, PyObject* args)
{
int low, high;
double *pr;
// maybe something about PyObject *pr ?
if (!PyArg_ParseTuple(args, "iiO", &low, &high, &pr))
return NULL;
// how to pass list pr to _asdf?
return Py_BuildValue("i", _asdf(low, high, pr));
}
static PyMethodDef AsdfMethods[] =
{
{"asdf", asdf, METH_VARARGS, "..."},
{NULL, NULL, 0, NULL}
};
PyMODINIT_FUNC
initasdf(void)
{
(void) Py_InitModule("asdf", AsdfMethods);
}
Building the module with setup.py :
from distutils.core import setup, Extension
module1 = Extension('asdf', sources = ['asdf_module.c'])
setup (name = 'asdf',
version = '1.0',
description = 'This is a demo package',
ext_modules = [module1])
Using the module in test_module.py :
import asdf
print asdf.asdf(-2, 3, [0.7, 0.0, 0.1, 0.0, 0.0, 0.2])
However, what I got as an output is :
pr[0] = 0.000000
pr[1] = 0.000000
pr[2] = 0.000000
pr[3] = 0.000000
pr[4] = 0.000000
pr[5] = -nan
Also, instead of _asdf returning 0, how can it return an array of n values (where n is a fixed number)?
oparameter is used to get aPyObject *. So you need to fix that up, and keep parsing.Ask Questionbutton in the top right hand corner. Thanks!