Finding the simplest way to wrap a double->double C function to Python
Question: I need to wrap a C function of interface

    
    
    double foo(double)
    

to python, so that in python console

    
    
    >>foo_py(2.9)
    

should give me the double value of foo(2.9). Eventually, I use the exported
foo_py in scipy.

I have been looking for the _simplest_ way to wrap such a C function.There are
certainly many related posts on stackoverflow, but they are dated a couple of
years ago and at this moment I am looking for an updated answer for my
specific demand. Thanks.

[EDIT] For information, I tried with C extension using PyObj etc. The
documentation on this seems lacking. I also tried with Boost.Python that wraps
C++ functions to Python. Here I need to wrap C functions (in order to avoid
naming demangling issues, etc).


Answer: Here is a simple example of how to do it:

**test.c**

    
    
    #include <Python.h>
    
    static PyObject* foo(PyObject* self, PyObject* args) {
      double d;
      PyArg_ParseTuple(args, "d", &d);
      return Py_BuildValue("d", d);
    }
    
    // Bind python function to C function
    static PyMethodDef simplemodule_methods[] = {
      {"foo_py", foo, METH_VARARGS},
      {NULL, NULL, 0}
    };
    
    // Initialize module
    void inittest() {
      (void) Py_InitModule("test", simplemodule_methods);
    }
    

**test.py**

    
    
    from test import *
    print foo_py(2.9) # will output 2.9
    

Compile with

`gcc -shared -fPIC -I/usr/include/python2.7 -o test.so test.c`

Run with

`python test.py`

