Strange problem with C API
John Machin
sjmachin at lexicon.net
Tue Feb 26 17:02:54 EST 2002
amrit040 at yahoo.com (Amrit) wrote in message news:<71c0a06e.0202260513.4b67841f at posting.google.com>...
> Hi
>
> I'm trying to write a C function callable from python. I'm getting
> some strange results :
> float x[N];
> float Thr;
> float sum;
> float max,min;
Don't you mean double???????????
> obj[i] = PySequence_GetItem (vec, i+1);
(1) This is Python & C, not FORTRAN. Lose the '+1'.
(2) There is no need to have an array obj[], a scalar obj will do.
(3) You need to test the result.
obj = PySequence_GetItem (vec, i);
if (obj == NULL) return NULL;
// :-) This is typically author stuffup, not caller stuffup.
> PyArg_Parse (obj[i], "f", &x[i]);
(1) This is most likely what is causing the exception that you are
getting -- the first arg to this function should be a *tuple*.
(2) This is not a recommended way of doing things. Try something like
this:
if (PyInt_Check(obj))
x[i] = (double)PyInt_AsLong(obj);
else if (PyFoo_Check(obj))
x[i] = (double)PyFoo_AsCFoo(obj);
// etc etc
else if (PyFloat_Check(obj))
x[i] = PyFloat_AsDouble(obj);
else {
raise_an_exception(..........);
// You read the manual or look at others' code, to find out how.
return NULL;
}
Py_DECREF(obj); // Don't forget this, else you will leak memory.
#### If anybody knows how to call the equivalent of the built-in
float() from C, please post.
However, what does your algorithm really need as its first arg: An
array of (Python) floats? An array of (Python) ints? A simple int
(like 15 in your example and in your comments) from which your
implementation will build an array of doubles 0.0, 1.0, ...., 14.0?
> My python implemtation of the same algo works just fine !
Famous last words?
More information about the Python-list
mailing list