Python Advanced Tutorial 9 - C Extensions

preview_player
Показать описание
This is tutorial on how to extend Python with the C Programming Language. All Links and Slides will be in the description. Subscribe for more cool stuff!

If you like what you see be sure to subscribe and thumbs up!
Рекомендации по теме
Комментарии
Автор

With Python 3.x the way extensions are written has changed. instead of the "PyMODINIT_FUNC initmyModule(void)" you now use a static structure of "PyModuleDef" which holds all the information to your module and then use PyInit_MyModule(void) and create the Module inside of that Function with PyModule_Create

this would be the new Source Code:

#include<Python.h>

int Cfib(int n)
{
if(n < 2)
return n;
else
return Cfib(n-1) + Cfib(n-2);
}

static PyObject* fib(PyObject* self, PyObject* args)
{
int n;

if (!PyArg_ParseTuple(args, "i", &n))
return NULL;

return Py_BuildValue("i", Cfib(n));
}

static PyObject* version(PyObject* self)
{
return Py_BuildValue("s", "Version: 1.0");
}

static PyMethodDef myMethods[] = {
{"fib", fib, METH_VARARGS, "Calculates the Fibonacci number."},
{"version", (PyCFunction)version, METH_NOARGS, "Returns the version."},
{NULL, NULL, 0, NULL}
};


static struct PyModuleDef myModule = {
PyModuleDef_HEAD_INIT,
"myModule", /* Module Name */
NULL, /* Optional Module Description */
-1,
myMethods /* Methods Array */
/* Along with a few other optional parameters just look PyModuleDef up*/
};

PyMODINIT_FUNC PyInit_myModule(void)
{
return PyModule_Create(&myModule);
}



The best Way to make it compatible with Python 3.x and older versions would be to include both ways to Initialize a module by separating them with the following Preprocessor definition

#if PY_MAJOR_VERSION >= 3
/*Put the new Initialization here*/
#else
/*The old one here*/
#endif


There are probably spelling mistakes in the source so dont expect this to compile right away :P

Автор

I am astonished at no comments despite so many views, this is for python2.x and not 3, there are few changes needed to be made to make it work in python3

HealmBreaker