Suppose we have given a C code and it needs to be accessed as a C extension module. So, for the given task – Swig Wrapper Generator is used.
Swig operates by parsing C header files and automatically creating extension code. C-header file is needed first, to use Swig. Give an example of C-header file in the code below.
Code #1 :
After having the header file, the next step is to write a Swig “interface” file. By convention, these files have a .i suffix and might look similar to the following.
Code #2 :
Code #3 : Mapping
Once the interface file is ready, Swig is invoked as a command-line tool
Code #4 :
The output of swig is two files –
work.py. work.py file is what users import and the work_wrap.c file is C code that needs to be compiled into a supporting module called
_work. It is performed using the same techniques as for normal extension modules. For example, creating a
setup.py file as shown in the code below –
Code #5 :
Code #6 : Compile and test, run python3 on the setup.py
After performing all the tasks, we can use the C extension module in a very easy way.
Code #7 :
GCD : 4 Divide : [5, 2] Distance between pt1 and pt2 : 2.8284271247461903 Distance between pt1 and pt2 : 2.0 Distance between pt1 and pt2 : 3.0 Average : 4.0
- Cython to Wrap Existing C Code
- Wrapping C/C++ for Python using SWIG - Set 1
- Python | Pandas Series.str.wrap()
- Python code to convert SOP to POS
- Code introspection in Python
- Chain Code for 2D Line
- Issues with using C code in Python | Set 2
- Issues with using C code in Python | Set 1
- Code Golfing in Python
- Hamming Code implementation in Python
- Python code formatting using Black
- Packaging and Publishing Python code
- Debugging Python code using breakpoint() and pdb
- Different Python IDEs and Code Editors
- Top 10 Python IDE and Code Editors in 2020
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.