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?

  1. 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.
  2. We have a large, stable and tested library in C/C++, which will be advantageous to use.
  3. 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++

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <iostream>
class Geek{
    public:
        void myFunction(){
            std::cout << "Hello Geek!!!" << std::endl;
        }
};
int main()
{
    // Creating an object
    Geek t; 
  
    // Calling function
    t.myFunction();  
   
    return 0;
}

chevron_right


We have to provide those cpp declarations as extern “C” because ctypes can only interact with C functions.



C++

filter_none

edit
close

play_arrow

link
brightness_4
code

extern "C" {
    Geek* Geek_new(){ return new Geek(); }
    void Geek_myFunction(Geek* geek){ geek -> myFunction(); }
}

chevron_right


Now, compile this code to the shared library :

Finally, write the python wrapper:

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# import the module
from ctypes import cdll
  
# load the library
lib = cdll.LoadLibrary('./libgeek.so')
  
# create a Geek class
class Geek(object):
  
    # constructor
    def __init__(self):
  
        # attribute
        self.obj = lib.Geek_new()
  
    # define method
    def myFunction(self):
        lib.Geek_myFunction(self.obj)
  
# create a Geek class object
f = Geek()
  
# object method calling
f.myFunction()

chevron_right


Output :

Hello Geek!!!

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.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.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.