Let’s discuss an extension module that needs to handle a pointer to a C data structure, without exposing any internal details of the structure to Python. Opaque data structures can be easily handled by wrapping them inside capsule objects as shown in the code snippet below.
Code #1 :
Refer Prev Article to find the distance() function – Using C codes in Python.
Code #2 : Code given is an extension code that wraps the Point structure and
distance() function using capsules.
Code #3 : Using the above function in Python
pt1 : <capsule object "Point" at 0x1004ea330> pt2 : <capsule object "Point" at 0x1005d1db0> Distance : 2.8284271247461903
- Capsules are similar to a typed C pointer.
- They hold a generic pointer along with an identifying name and can be easily created using the
PyCapsule_GetPointer()function is used to extract the pointer contained inside a capsule.
- Garbage collection and memory management is a tricky part that concerns about the capsules.
PyPoint_FromPoint()function accepts a must_free argument that indicates whether the underlying Point * structure is to be collected when the capsule is destroyed.
- Python Modules
- Reloading modules in Python
- Dividing a Large file into Separate Modules in C/C++, Java and Python
- C Extension Module using Python
- C API from Extension Module in Python | Set 1
- C API from Extension Module in Python | Set 2
- Python | Passing Filenames to Extension in C
- Python | Repeat and Multiply list extension
- Python | Extension function operating on Arrays
- Python | Sort and store files with same extension
- Reading Python File-Like Objects from C | Python
- Python | Index of Non-Zero elements in Python list
- Python | Merge Python key values to list
- Important differences between Python 2.x and Python 3.x with examples
- Python | Add Logging to a Python Script
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.