Using C++ in Python

Unreio
2 min readJan 17, 2023

--

Hi, I’m Unreio and in this post I’m going to tutorial you how to use C++ in Python

But before starting, you may ask yourself this question, what is the use of this work?

Speed

First of all, speed. Python is a high-level and simple language, but what makes it difficult to do many things with it is its very low speed, because Python is an interpreted language.

access

Another problem with Python is its very low accessibility. Although Python is a complete language, it still lacks a series of libraries and features, and you need lower-level languages such as C or C++ to do those things.

I don’t want to take more of your time, so let’s go straight to the training

Start programming

Well, first of all, I will make a simple function that prints only one thing.
Now, if I want to consider this function outside the program, for example, as a library function, I have to put it in extern C

Of course, make sure that the name of the function you put in extern C can be called in other languages

Now, if we want to use this function in Python, we first need to convert our C++ file into a library, so we do this in the terminal with this command.

Now, using the ctypes library, we import the library we created into Python and then call it with the name of its function.

And now if you run the file, you will see that your output is hello world

But if our function returns something to us, for example a string
Or if we want to give a specific input to the function, what should we do there?
This is the end of our post, but if you are looking for an answer to this question, you should watch the video I made for you to get all the answers.

goodbye until the next posts

--

--