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.
========== wrap.c =========
#include <Python.h>
PyObject *wrap_fact(PyOb ject *self, PyObject *args)
{
double n=0.0,result=0. 0;
if (!PyArg_ParseTu ple (args,"d:fact", &n))
return NULL;
result = fact(n);
result = fact(result);
return Py_BuildValue(" d",result);
}
PyObject *wrap_test(PyOb ject *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:
lyb@ubuntu:~$ gcc -fpic -c -I. -I.. -I/usr/include/python2.4/ example.c
wrap.c
lyb@ubuntu:~$ gcc -shared -o example.so example.o wrap.o
then i used the example.so with command:
lyb@ubuntu:~$ python -c "import example; print example.fact(0. 444)"
n=0.444000
n=-103079215.00000 0 <-- Why not is 0.444?
-1140850688.0 <--- Why not is 0.444?
I have a problem of float return error in python c binding module.
Below is my c sources, compile commands and result of program.
========== wrap.c =========
#include <Python.h>
PyObject *wrap_fact(PyOb ject *self, PyObject *args)
{
double n=0.0,result=0. 0;
if (!PyArg_ParseTu ple (args,"d:fact", &n))
return NULL;
result = fact(n);
result = fact(result);
return Py_BuildValue(" d",result);
}
PyObject *wrap_test(PyOb ject *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:
lyb@ubuntu:~$ gcc -fpic -c -I. -I.. -I/usr/include/python2.4/ example.c
wrap.c
lyb@ubuntu:~$ gcc -shared -o example.so example.o wrap.o
then i used the example.so with command:
lyb@ubuntu:~$ python -c "import example; print example.fact(0. 444)"
n=0.444000
n=-103079215.00000 0 <-- Why not is 0.444?
-1140850688.0 <--- Why not is 0.444?
Comment