* Namen: Timo Migchielsen en Joris Wes
* Datum: 1-12-2022
* Omschrijving: Python Bindings with C++
# Python bindings met c++
Er zijn verschillende manieren om Python bindings met C++ te maken. De keuze voor een specifieke methode kan afhangen van verschillende factoren, zoals de specifieke behoeften van het project.
Een van de meest populaire manieren om Python bindings met C++ te maken, is door gebruik te maken van de ctypes library. De ctypes library is een module in de standaard Python bibliotheek, en het maakt het mogelijk om externe bibliotheken te laden en hun functies aan te roepen vanuit Python. Dit kan handig zijn als je bijvoorbeeld een C++ bibliotheek hebt die je wilt gebruiken in een Python programma, of als je een Python programma wilt maken dat gebruik maakt van de snelle berekeningen van C++.
Er zijn ook andere tools en bibliotheken beschikbaar, zoals PyBind11 en Cython. Deze kunnen ook worden gebruikt om Python bindings met C++ te maken. Elke optie heeft zijn eigen voor en nadelen en de beste keuze voor jouw project kan afhangen van de specifieke behoeften van het project en je eigen voorkeuren als ontwikkelaar.
Wij hebben ervoor gekozen om ctypes library te gebruiken voor onze programma's.
Het eerste programma is het maken van een Fibonacci programma. Met dit programma laten wij goed zien dat deze functie veel sneller is met C++ dan in Python.
Het tweede programma is het doorgeven van een array van Python naar C++, de functie telt alle getallen bij elkaar op. Ook hier blijkt het C++ programma sneller dan het Python programma.
Het derde programma is het doorgeven van een klasse van Python naar C++. Deze klasse heeft XYZ coordinaten als variabelen. Deze klasse wordt vervolgens gebruikt in C++.
## Tutorial - Creeren van een shared library
Om gebruik te maken van C++ functies in Python, moet er een gedeelde library aangemaakt worden. Je maakt de gedeelde library van het C++ bestand. Deze library wordt in Python geïmporteerd, zodat je de C++ functies uit die library kan geruiken.
De volgende stappen moet je eenmalig uitvoeren, om gebruik te kunnen maken van de gcc compiler in de Windows Terminal.
**Stap 1:** Installeer MinGW
**Stap 2:** Voeg MinGW toe aan de omgevingsvariabelen van Windows: Rechtermuisklik op "Deze PC" > Eigenschappen > Geavanceerde systeeminstellingen > Omgevingsvariabelen
**Stap 3:** Ga in omgevingsvariabelen naar path. Klik daar op Nieuw en geef de locatie op van de minGW bin map.
Nu we gcc kunnen gebruiken in de windows terminal kunnen we een C++ library gaan compilen naar een shared library en gaan gebruiken in Python. Deze stappen moeten elke keer worden doorlopen als je iets aanpast in de C++ code.
**Stap 1:** Ga naar de C++ code die je wilt gebruiken in Python.
**Stap 2:** Plaats de code tussen de volgende regels:
```cpp
extern "C"{
}
```
Dit is nodig zodat Python de functie kan herkennen, als je ze hier niet in plaatst dan kunnen de functies niet gebruikt worden in Python.
**Stap 3:** Compile de code naar een gedeelde library met gcc.
```
gcc -fPIC -shared -o clibrary.so clibrary.cpp
```
Hierin kun je clibrary veranderen in een naam naar eigen keuze.
**Stap 4:** Importeer de gedeelde library in Python.
```python
path = os.getcwd()
clibrary = ctypes.CDLL(os.path.join(path, 'clibrary.so'))
```
De path variabele wordt gebruikt om de path variabele te pakken van de console. Hierdoor is het niet nodig om elke keer de specifieke locatie op te geven. Als je in de vorige stap de library een andere naam hebt gegeven, moet dit in Pyton ook gedaan worden.
## Tutorial - C++ functie aanroepen in Python
Voor de tutorial wordt de volgende C++ code gebruikt:
```cpp
#include <stdio.h>
extern "C" {
unsigned int fibonacci(const unsigned int n)
{
if (n < 2){
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
```
**Stap 1:** Creëer en importeer een gedeelde library (Zie Tutorial - Creëren van een shared library).
**Stap 2:** Importeer ctypes bovenaan je Python code
```python
import ctypes
```
**Stap 3:** Voeg de functie toe aan Python
```python
fibonacci = clibrary.fibonacci
```
**Stap 4:** Geef aan welk type variabelen de argumenten zijn:
```python
fibonacci.argtypes = [ctypes.c_uint]
```
Dit is nodig, omdat Python een andere manier heeft van geheugen opslaan dan C++.
**Stap 5:** Geef aan welk type variabele de functie returned:
```python
fibonacci.restype = ctypes.c_uint
```
**Stap 6:** Roep de functie aan.
```python
fibonacci(38)
```
Het is ook mogelijk om een waarde mee te geven die in een variabele staat.
## Testen - Fibonacci python vs C++
Met de volgende code kun je testen hoeveel het scheelt om een C++ functie te gebruiken in plaats van de Python functie:
```python=
import ctypes
import time
import os
path = os.getcwd()
clibrary = ctypes.CDLL(os.path.join(path, 'clibrary.so'))
fibinacci = clibrary.fibinacci
fibinacci.argtypes = [ctypes.c_uint]
fibinacci.restype = ctypes.c_uint
def fibinacci_py(x):
if x < 2:
return x
return fibinacci_py(x - 1) + fibinacci_py(x - 2)
n = 38
print('Python:')
start_time = time.perf_counter_ns()
print('Answer:', fibinacci_py(n))
print('Time:', (time.perf_counter_ns() - start_time) / 1e9, 's')
print()
print('C++:')
start_time = time.perf_counter_ns()
print('Answer:', fibinacci(n))
print('Time:', (time.perf_counter_ns() - start_time) / 1e9, 's')
```
Dit gaf bij ons het volgende resultaat:
```
Python:
Answer: 39088169
Time: 10.1444601 s
C++:
Answer: 39088169
Time: 0.2065866 s
```
Hierin is te zien dat de C++ functie veel sneller is dan de Python functie.
## Tutorial - Array argument
Voor de tutorial wordt de volgende C++ code gebruikt:
```cpp=
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
extern "C" {
int sumArray(int *arr, int size) {
int sum = 0;
for (int i = 0; i<size; i++){
sum += arr[i];
}
return sum;
}
}
```
**Stap 1:** Creëer en importeer een gedeelde library (Zie Tutorial - Creëren van een shared library).
**Stap 2:** Importeer ctypes bovenaan je Python code
```python
import ctypes
```
**Stap 3:** Maak een array aan in Python:
```python
values = (ctypes.c_int * array_size)()
```
In dit geval is values een array van array_size keer een integer.
**Stap 4:** Vul de array
```python
for i in range(len(values)):
values[i] = i
```
Het is niet perse nodig om een array aan te maken met dezelfde waardes als hier. In de array kun je elke integer waarde opslaan.
**Stap 5:** Voeg de functie toe aan Python
```python
sum = clibrary.sumArray(values, len(values))
```
**Stap 6:** Geef aan welk type variabelen de argumenten zijn:
```python
sum.argtypes = [ctypes.POINTER(ctypes.c_int), ctypes.c_int]
```
Dit is nodig, omdat Python een andere manier heeft van geheugen opslaan dan C++.
**Stap 7:** Geef aan welk type variabele de functie returned:
```python
sum.restype = ctypes.c_int
```
**Stap 8:** Roep de functie aan in Python
```python
sum(values, len(values))
```
## Testen - Som van Array Pyton vs C++
Met de volgende code kun je testen hoeveel het scheelt om een C++ array functie te gebruiken in plaats van de Python array functie:
```python=
import ctypes
import os
import time
path = os.getcwd()
clibrary = ctypes.CDLL(os.path.join(path, 'clibrary.so'))
array_size = 5000
values = (ctypes.c_int * array_size)()
def py_sumArray(arr):
sum = 0
for element in arr:
sum += element
return sum
for i in range(len(values)):
values[i] = i
sum = clibrary.sumArray
sum.argtypes = [ctypes.POINTER(ctypes.c_int), ctypes.c_int]
sum.restype = ctypes.c_int
print('Python:')
start_time = time.perf_counter_ns()
print('Answer:', py_sumArray(values))
print('Time:', (time.perf_counter_ns() - start_time) / 1e9, 's')
print()
print('C++:')
start_time = time.perf_counter_ns()
print('Answer:', sum(values, len(values)))
print('Time:', (time.perf_counter_ns() - start_time) / 1e9, 's')
```
Dit gaf bij ons het volgende resultaat:
```
Python:
Answer: 12497500
Time: 0.0009124 s
C++:
Answer: 12497500
Time: 0.0001883 s
```
Hierin is te zien dat de C++ array functie sneller is dan de Python array functie.
## Tutorial - C++ Structures in Python
In deze tutorial wordt uitgelegd hoe je C++ Structures kan gebruiken in Python. Voor deze tutorial wordt de volgende code gebruikt:
```cpp=
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
extern "C" {
struct Coordinate{
int x;
int y;
int z;
};
struct CoordinateArray{
struct Coordinate coordinates[10];
} ;
void printCoordinate(struct Coordinate c){
printf("x: %d, y: %d, z: %d\n", c.x, c.y, c.z);
}
void printCoordinateArray(struct CoordinateArray ca) {
for (int i = 0; i < 10; i++) {
printf("%d: x:%d y:%d z:%d\n", i+1, ca.coordinates[i].x, ca.coordinates[i].y, ca.coordinates[i].z);
}
}
}
```
**Stap 1:** Creëer en importeer een gedeelde library (Zie Tutorial - Creëren van een shared library).
**Stap 2:** Importeer ctypes bovenaan je Python code
```python
import ctypes
```
**Stap 3:** Voeg de functie toe aan Python
```python
printCoordinate = clibrary.printCoordinate
```
**Stap 4:** Geef aan welk type variabelen de argumenten zijn:
```python
printCoordinate.argtypes = [ctypes.Structure]
```
**Stap 5:** Maak een Python class
```python
class Coordinate(ctypes.Structure):
_fields_ = [("x", ctypes.c_int),
("y", ctypes.c_int),
("z", ctypes.c_int)]
```
Deze class moet dezelfde structuur hebben als de structure in C++. Bij elke variable moet worden aangegeven welk type variabele het is.
**Stap 6:** Maak een variabele aan met de Python class
```python
c1 = Coordinate(142, 122, 80)
```
**Stap 7:** Roep de functie aan
```python
printCoordinate(c1)
```
## Testen - Print coordinaten via C++ in Python
Met de volgende code kun je coördinaten printen via C++ in Python.
Hiervoor wordt de volgende Python code gebruikt:
```python=
import ctypes
import os
import time
path = os.getcwd()
clibrary = ctypes.CDLL(os.path.join(path, 'clibrary.so'))
printCoordinate = clibrary.printCoordinate
printCoordinate.argtypes = [ctypes.Structure]
printCoordinateArray = clibrary.printCoordinateArray
printCoordinate.argtypes = [ctypes.Structure]
class Coordinate(ctypes.Structure):
_fields_ = [("x", ctypes.c_int),
("y", ctypes.c_int),
("z", ctypes.c_int)]
class CoordinateArray(ctypes.Structure):
_fields_= [("coordinates", Coordinate * 10)]
c1 = Coordinate(142, 122, 80)
c2 = Coordinate(243, 122, 80)
c3 = Coordinate(345, 122, 80)
c4 = Coordinate(448, 122, 80)
c5 = Coordinate(545, 122, 80)
c5 = Coordinate(643, 122, 80)
c6 = Coordinate(742, 122, 80)
c7 = Coordinate(842, 122, 80)
c8 = Coordinate(945, 122, 80)
c9 = Coordinate(456, 122, 80)
c10 = Coordinate(123, 242, 12)
coordinates = (c1, c2, c3, c4, c5, c6, c7, c8, c9, c10)
coordinateArray = CoordinateArray(coordinates)
printCoordinate(c1)
printCoordinateArray(coordinateArray)
```
Deze code levert het volgende resultaat op:
```
x: 142, y: 122, z: 80
1: x:142 y:122 z:80
2: x:243 y:122 z:80
3: x:345 y:122 z:80
4: x:448 y:122 z:80
5: x:643 y:122 z:80
6: x:742 y:122 z:80
7: x:842 y:122 z:80
8: x:945 y:122 z:80
9: x:456 y:122 z:80
10: x:123 y:242 z:12
```
# Resultaat en conclusie
Het gebruik van Python bindings met C++ kan een effectieve manier zijn om berekeningen in Python sneller te maken. Afhankelijk van de specifieke behoeften van het project en de gebruikte techniek, kan het gebruik van Python bindings met C++ leiden tot aanzienlijke snelheidsverbeteringen, zoals in onze test waarbij het 60x zo snel bleek te zijn.
Het is echter belangrijk om te onthouden dat het gebruik van Python bindings met C++ niet altijd de beste oplossing is, en dat het afhangt van de specifieke behoeften van het project. Soms kan het gebruik van Python bindings met C++ leiden tot meer complexe code of kan het moeilijker zijn om te onderhouden. Het is daarom aan te raden om de verschillende opties te overwegen en te bepalen welke het beste past bij jouw specifieke projectbehoeften
# Referenties
Python documentation on ctypes - This page provides an overview of the ctypes library and how it can be used to create Python bindings with C++.
https://docs.python.org/3/library/ctypes.html
Cython documentation - Cython is a tool that allows you to write C-extensions for Python using syntax that is very close to Python itself. It can be used to create Python bindings with C++.
https://cython.org/
PyBind11 documentation - PyBind11 is a lightweight header-only library that allows you to create Python bindings with C++.
https://pybind11.readthedocs.io/en/stable/
Creating Python modules in C/C++ - tutorial - This tutorial from the official Python documentation provides an in-depth guide on how to create Python modules in C or C++.
https://docs.python.org/3/extending/extending.html
Creating shared libraries in C/C++ - tutorial - This tutorial provides a step-by-step guide on how to create shared libraries in C or C++ using the gcc compiler.
https://www.tutorialspoint.com/cprogramming/c_dynamic_memory_allocation.htm
Python documentation on ctypes. (n.d.). In Python 3 documentation. Retrieved from https://docs.python.org/3/library/ctypes.html