TimoMigchielsen
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    * 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

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully