In this article we will see: how to create libraries for Python with C++, the process is similar to the post/video we saw on C++ for Lua.
The libraries of several programming languages are written in C and C++, as the performance is much higher than writing in the language itself.
There are a large number of libraries for Python that are written in C++, the most famous are:
Creating a basic Hello World
Let’s create a directory (libpycpp/
) and a main.cpp
file:
01. Most basic code of all: Prints: Hello World
main.cpp
To compile:
Using:
vim script.py
02. Using parameters for function
1. Create a new base function:
2. Create the return
3. Add to array
Using:
vim script.py
python script.py
03. Creating a function that receives string
- Let’s call this function
echo
:
PyObject
function:
- Add to the array:
Compile and test:
I made the library of that code from video that plays MP3 with C++ and created a lib.
If you want to test on your machine, follow the steps:
i1. Copy and create the files (playmp3.hpp
and playmp3.cpp
) from the playmp3 video post available at:
🎶 How to Play MP3 with C++ 🎻 🎼 Code Music
- Create
main.cpp
and add the code below:
- Add the libalsa.so path to the environment variable:
LD_LIBRARY_PATH
:
- Close and open the terminal or run the command below:
- Compile:
- Create a Python file:
player.py
In music.mp3
replace with the song you want to listen to!
Then just run:
If you want to use the library directly on your system:
If you want to use a different output plugin for libao
, such as the “oss” (Open Sound System) plugin, use:
Watch the video
The video is in Portuguese, but it is possible to follow it even without audio.
For more information, visit: https://docs.python.org/3/c-api/index.html
python
cpp
clanguage
Marcos Oliveira
Software developer