Helloworld with Python C extension

Stefan Behnel stefan_ml at behnel.de
Mon Aug 29 17:34:22 EDT 2016


Ganesh Pal schrieb am 29.08.2016 um 19:30:
> I need you input on the below  hello world program.  I a m trying to add a
> python binding which will return the character for the given index .  I am
> on Python 2.7   and linux
> 
> Example :
> >>> string ='helloworld'
> >>> dda_hello(5)
> >>> 'w'
> 
>  /*
> + * Hello world example for python bindings
> + */
> +
> +static char* string = "helloworld";
> +char dda_hello(int i)
> +     {
> +      return string[i];
> +     }
> +
> +static PyObject *
> +py_dda_hello(PyObject *self, PyObject *args )
> +{
> +       int index;
> +       char char1;
> +       if (!PyArg_ParseTuple(args, "i", &index))
> +               return NULL;
> +       char1 = dda_hello(index);
> +       return Py_BuildValue("s",char1);
> +}
> +
> +/*
> 
> @@ -1674,6 +1705,10 @@ PyMethodDef xyz_methods[] = {
> +        {"dda_hello", py_dda_hello, METH_VARARGS,
> +                "Returns the character entered for a given index"},

Here's a Cython implementation (http://cython.org) of your example:

    cdef str string = "helloworld"

    def dda_hello(int i):
        return string[i]

It uses a lot less code than the C-implemented version, but is compatible
with Python 2 and Python 3 and avoids pitfalls like the crash you are
seeing, as well as raising a proper IndexError for invalid index arguments
(and it supports negative indexing). I also wouldn't be surprised if it's
visibly faster than your C implementation.

Unless your intention is to explicitly learn how to use the CPython C-API,
you should give Cython a try instead.

Stefan





More information about the Python-list mailing list