One, C level module add API
We still operate on the following structures,
#include <math.h>typedef struct Point { double x, y;} Point;
The objective of this section is to encapsulate the two-point struct's operation function as the C-level API of sample library, which can be called by C library other than sample, first write the following function pointer struct instance,
/* pysample.c */static pyobject *pypoint_frompoint (point *p, int must_free) { /* capsules and C-pointers are similar. Internally, they get a generic pointer and a name that can be easily created using the Pycapsule_new () function. In addition, an optional destructor can be bound to the capsule to release the underlying memory when the capsule object is garbage collected * /return pycapsule_new (P, "point", Must_free del_point:null);} /* Utility functions */static point *pypoint_aspoint (Pyobject *obj) { return (point *) pycapsule_getpointer (obj, "Poi NT ");} Static _pointapimethods _point_api = { pypoint_aspoint, pypoint_frompoint};
The structure is defined as follows, in a new header function
/* pysample.h *//* Public API table *//* The most important part here is the function pointer table _pointapimethods. It is initialized when the module is exported, and then is found when the module is imported. */typedef struct {point * (*aspoint) (Pyobject *); Pyobject * (*frompoint) (point *, int);} _pointapimethods;
"Python coolbook" C extension Library-its five _c language level Python libraries call API (to be continued)