Nous continuons le sujet de la façon d'appeler C / C ++ à partir de Python3 . Maintenant, nous utilisons l' API C pour créer le module, dans cet exemple, nous pouvons comprendre comment cffi et d'autres bibliothèques simplifient nos vies. Parce qu'à mon avis, c'est la voie la plus difficile.
C
Une bibliothèque de tests pour montrer comment travailler avec des variables globales, des structures et des fonctions avec des arguments de différents types. Dans mes articles, j'utilise des variantes de la même bibliothèque, selon la méthode que j'utilise maintenant. Liens vers les méthodes précédentes ci-dessous.
test.h
typedef struct test_st_s test_st_t; extern int a; extern double b; extern char c; static PyObject *func_hello(PyObject *self, PyObject *args); static PyObject *func_ret_int(PyObject *self, PyObject *args); static PyObject *func_ret_double(PyObject *self, PyObject *args); static PyObject *func_ret_str(PyObject *self, PyObject *args); static PyObject *func_many_args(PyObject *self, PyObject *args); static PyObject *func_ret_struct(PyObject *self, PyObject *args); struct test_st_s { PyObject_HEAD
test.c
Le module doit indiquer qu'il comprendra: fonctions, variables globales et structures. Chacune de ces choses doit être décrite, la chose la plus difficile pour ses types de données (structure ...) Environ un tel fichier est généré par cffi .
Pour fonctionner, vous devez connecter les fichiers d'en-tête:
#include <Python.h> #include <structmember.h> //
Indicateurs de compilation:
$(python3-config --includes --ldflags) -fPIC
La fonction suivante est responsable du traitement des arguments:
PyArg_ParseTuple(args, "ids", &val1, &val2, &val3);
Le premier est un argument de type int, il a la désignation de lettre i
2e flotteur / double - d
3e chaîne - s
Toutes les désignations de lettres possibles des types de données peuvent être trouvées ici.
Passons maintenant à la description de la façon de décrire la structure.
struct.c:
Et c'est tout pour:
struct test_st_s { PyObject_HEAD
D'accord, pas un peu. De plus, des méthodes peuvent être définies pour la structure (par exemple, test_st_print ).
Dans le code, j'essaie de faire plus de commentaires pour décrire séparément moins.
Python
Un exemple de travail avec un module C de Python :
import sys import time
Le module est devenu natif.
Avantages et inconvénients de l'API C
Avantages :
- facile à utiliser en python
Inconvénients :
- difficile de décrire vos types de données dans l' API C
- il est difficile pour les programmeurs purs d'implémenter pour Python , et pas pour eux non plus ... (pour moi, le plus simple est par le biais de ctypes )
- module (bibliothèque) sera uniquement pour Python
Le temps d'exécution moyen des tests sur chaque méthode avec 1000 démarrages:
- ctypes: - 0,0004987692832946777 secondes ---
- CFFI: - 0,00038521790504455566 secondes ---
- pybind: - 0,0004547207355499268 secondes ---
- API C: - 0,0003561973571777344 secondes ---
Les références