YunBin Lee wrote: > Hi, all. > I have a problem of float return error in python c binding module. > Below is my c sources, compile commands and result of program.
There seems to be a missing file: example.h. If that hint isn't sufficient, please continue reading. > > ========== wrap.c ========= > #include <Python.h> > > PyObject *wrap_fact(PyObject *self, PyObject *args) > { > double n=0.0,result=0.0; > if (!PyArg_ParseTuple (args,"d:fact",&n)) > return NULL; > result = fact(n); > result = fact(result); > return Py_BuildValue("d",result); > } > > PyObject *wrap_test(PyObject *self, PyObject *args) > { > double value = 0.124; > return Py_BuildValue ("d", value); > } > > static PyMethodDef exampleMethods[] = > { > {"fact", wrap_fact, METH_VARARGS, "Simple return a float"}, > {"test", wrap_test, METH_VARARGS, "Test"}, > {NULL,NULL} > }; > > void initexample() > { > PyObject *m; > m = Py_InitModule ("example", exampleMethods); > } > ========== end wrap.c ========= > > ========== example.c ========= > #include <stdio.h> > > double fact(double n) > { > printf ("n=%f\n",n); > return n; > } > > int main(int argc,char *argv[]) > { > printf ("%f\n",fact(0.1234)); > } > ========== end example.c ========= > > complied with commands: > [EMAIL PROTECTED]:~$ gcc -fpic -c -I. -I.. -I/usr/include/python2.4/ example.c > wrap.c Didn't this produce any warning messages, like: wrap.c:8: warning: implicit declaration of function `fact' ? > [EMAIL PROTECTED]:~$ gcc -shared -o example.so example.o wrap.o > > then i used the example.so with command: > [EMAIL PROTECTED]:~$ python -c "import example; print example.fact(0.444)" > n=0.444000 > n=-103079215.000000 <-- Why not is 0.444? > -1140850688.0 <--- Why not is 0.444? Did you notice that the garbage is a whole number? Why? Because you have been (more or less) plucking ints out of some arbitrary place on the stack, floating them, and printing them. HTH, John -- http://mail.python.org/mailman/listinfo/python-list