Helloworld with Python C extension
MRAB
python at mrabarnett.plus.com
Mon Aug 29 13:58:27 EDT 2016
On 2016-08-29 18:30, Ganesh Pal wrote:
> Hello Team ,
>
> 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);
This bit is wrong:
> + return Py_BuildValue("s",char1);
The format "s" is for a null-terminated C string (char *), but you're
giving it a C int.
The format you should be using is "c" (C int representing a character).
> +}
> +
> +/*
>
> @@ -1674,6 +1705,10 @@ PyMethodDef xyz_methods[] = {
> + {"dda_hello", py_dda_hello, METH_VARARGS,
> + "Returns the character entered for a given index"},
>
>
>>>> import as.ds.dss as daa
>>>> print dda.dda_hello(1)
> zsh: segmentation fault (core dumped) python
>
> Apologies for posting the diff , I didn't find a better way
>
It would be a good idea to check the index and raise an exception if
it's out the bounds.
More information about the Python-list
mailing list