How to call C / C++ from Python?
In order to take advantage of the strength of both languages, developers use Python bindings which allows them to call C/C++ libraries from python.
Now, the question arises that why there is a need for doing this?
- As we know that, C has faster execution speed and to overcome the limitation of Global Interpreter Lock(GIL) in python, python bindings are helpful.
- We have a large, stable and tested library in C/C++, which will be advantageous to use.
- For performing large scale testing of the systems using Python test tools.
Let’s see the C code which we want to execute with Python :
C++
#include <iostream>
class Geek{
public :
void myFunction(){
std::cout << "Hello Geek!!!" << std::endl;
}
};
int main()
{
Geek t;
t.myFunction();
return 0;
}
|
We have to provide those cpp declarations as extern “C” because ctypes can only interact with C functions.
C++
extern "C" {
Geek* Geek_new(){ return new Geek(); }
void Geek_myFunction(Geek* geek){ geek -> myFunction(); }
}
|
Now, compile this code to the shared library :
Finally, write the python wrapper:
Python3
from ctypes import cdll
lib = cdll.LoadLibrary( './libgeek.so' )
class Geek( object ):
def __init__( self ):
self .obj = lib.Geek_new()
def myFunction( self ):
lib.Geek_myFunction( self .obj)
f = Geek()
f.myFunction()
|
Output :
Hello Geek!!!
Last Updated :
29 Jul, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...