// creation d'un module en C++ pour importation dans Python #include "Python.h" //########################################################################### // fonction 'fact' en C++ int fact(int n) { if (n < 2) return(1); return (n)*fact(n-1); }; //=========================================================================== // encapsulation de la fonction 'fact' pour utilisation par Python static PyObject * testext_fact(PyObject *self, PyObject *args) { int num; if (!PyArg_ParseTuple(args, "i", &num)) return NULL; return (PyObject*)Py_BuildValue("i", fact(num)); }; //########################################################################### // fonction 'pgcd' en C++ int pgcd(int a, int b) { int r; while (b!=0) { r = a%b; a = b; b = r; } return a; }; //=========================================================================== // encapsulation de la fonction 'pgcd' pour utilisation par Python static PyObject * testext_pgcd(PyObject *self, PyObject *args) { int a, b; if (!PyArg_ParseTuple(args, "ii", &a, &b)) return NULL; // cas où a ou b n'est pas un int return (PyObject*)Py_BuildValue("i", pgcd(a,b)); }; //########################################################################### // liste des objets disponibles du module static PyMethodDef testextMethods[] = { {"fact", testext_fact, METH_VARARGS}, {"pgcd", testext_pgcd, METH_VARARGS}, {NULL, NULL}, }; //########################################################################### // initialisation du module par Python pendant l'importation PyMODINIT_FUNC inittestext(void) { Py_InitModule("testext", testextMethods); };