Let’s write a C extension function that can operate on contiguous arrays of data, as might be created by the array module or libraries like NumPy and this function should be general purpose and not specific to any one array library.
The code should use Buffer Protocol to receive and process arrays in a portable manner. The code below is a C extension function that receives array data and calls the
avg(double *buf, int len) function from this article – Using C codes in Python.
Code #1 :
Code #2 : How this extension function works
Average : 2.0 Average numpy array : 2.0
Average list : Traceback (most recent call last): File "", line 1, in TypeError: 'list' does not support the buffer interface
PyBuffer_GetBuffer()function is the key to the code in the article.
- It tries to obtain the information about the memory representation in the given arbitrary Python object.
- It simply raises an exception and returns -1, if it is not possible to obtain information (as is the case with normal Python objects).
- The special flags passed to
PyBuffer_GetBuffer()give additional hints about the kind of memory buffer that is requested.
- As, PyBUF_ANY_CONTIGUOUS specifies that a contiguous region of memory is required.
- C API from Extension Module in Python | Set 1
- C API from Extension Module in Python | Set 2
- C Extension Module using Python
- Python | Passing Filenames to Extension in C
- Python | Repeat and Multiply list extension
- Python | Sort and store files with same extension
- Python | Opaque Pointers in C extension modules
- Intersection of two arrays in Python ( Lambda expression and filter function )
- Python Arrays
- Python | Using 2D arrays/lists the right way
- Set update() in Python to do union of n arrays
- Python | Broadcasting with NumPy Arrays
- Merge two sorted arrays in Python using heapq
- Python List Comprehension to find pair with given sum from two arrays
- intersection_update() in Python to find common elements in n arrays
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.