Home

Entwicklung eines Python-C-Moduls mit Visual Studio 2022

Das folgende Tutorial zeigt, wie man ein einfaches Python-C-Modul entwickelt und kompiliert ohne spezielle Python-Entwicklungsumgebungen wie PyDev oder PyInstaller.

Die Basis ist die Nutzung von Visual Studio 2022 für C/C++-Kompilierung. Nach dem Kompilieren wird ein .pyd-Modul erstellt, das in Python über ctypes verwendet werden kann.

Beispiel: Eine einfache Pythagoras-Berechnung sehr einfach, aber fehlt noch viel im Vergleich zu Modulen wie pyodbc, die z.B. SQL*Header und PyObject verwenden.

Wichtiger Hinweis: Visual Studio 2022 bietet keine direkte Möglichkeit, ein .pyd-Modul direkt zu erstellen. Die Kompilierung erfolgt daher über ein externes Build-Script (z.B. build.bat) mit gcc und MinGW.
Wichtiger Hinweis 2 (Juni 2026) : Das Tutorial ist etwas älter und wurde nochmal überarbeitet. Mittlerweile ist Visual Studio 2026 am Markt, die Visual Studio 2022 Community Version wird bei Anwendern in langsam durch die Lizenzbedingungen von Microsoft verschwinden. Visual Code ist Microsofts neueste Option, und für bestimmte Anwendungsfälle vielleicht brauchbarer als Visual Studio. Aber die häufigen Updates, der etwas eigenwillige C/C++ Support mit diversen Extensions, die dann wieder veralten, lassen mich eher auf Abstand zu diesem Produkt gehen.
Im Quellcode selber befinden sich √ und 2 Anzeigen, die mit HTML Codes formatiert wurden. Dies bitte beachten. Es gibt auch noch eine verbesserte Version, als Teil 2 veröffentlicht.
Das verbesserte Beispiel verwendet die gleichen Tools, aber nun sind Fehlerprüfung,en Klassen und pytest als Testverfahren, hinzugefügt worden. Viel Erfolg!

Projektstruktur (in VS)

pythagoras_project/
|
+-- pythagoras.c              C-Quellcode (für das Modul)
+-- pythagoras.py             Python-Wrapper mit ctypes
+-- main.py                   Testprogramm
+-- pythagoras_project.sln   Visual Studio Projekt
  

Erstellung des C-Moduls (pythagoras.c)

Erstelle ein neues Projekt in Visual Studio 2022 und füge die C-Datei hinzu:

Schritt 1: Neues Projekt erstellen
Schritt 2: Füge pythagoras.c hinzu

Inhalt von pythagoras.c

#include <math.h>

// Exportierte Funktionen für Python über ctypes
double aufstellen(double a, double b) {
    return a * a + b * b;
}

int kontrolliere(double a, double b, double c) {
    double a2 = a * a;
    double b2 = b * b;
    double c2 = c * c;
    return (abs(a2 + b2 - c2) < 1e-10) ? 1 : 0;
}

double wurzel(double a, double b) {
    return sqrt(a * a + b * b);
}

// Optional: Ausgabe-Funktion
void ausgabe_pythagoras(double a, double b, double c) {
    printf("Pythagoras: %f2 + %f2 = %f2\n", a, b, c);
}
Wichtige Hinweise:

Erstellung des .pyd-Moduls (Kompilierung)

Visual Studio 2022 bietet keine direkte Option, um ein .pyd-Modul zu erstellen. Daher muss das Modul über ein Build-Script kompiliert werden.

Schritt 4: Erstelle ein Build-Script

Inhalt von build.bat

@echo off
:: Kompiliere pythagoras.c zu ein Python-Modul (.pyd)

:: 1. Prüfe, ob MinGW installiert ist
where gcc >nul 2>&1
if %errorlevel% neq 0 (
    echo Fehler: MinGW (gcc) nicht gefunden!
    echo Bitte installiere MinGW unter: https://www.mingw-w64.org  bzw  https://www.msys2.org  Windows Port
    pause
    exit /b 1
)

:: 2. Erstelle den Ordner build/lib
if not exist build (
    mkdir build
)
if not exist build/lib (
    mkdir build/lib
)

:: 3. Kompiliere das Modul mit gcc
gcc -c pythagoras.c -o pythagoras.o
gcc -shared -fPIC -o build/lib/pythagoras.pyd pythagoras.o

echo Erfolgreich kompiliert: build/lib/pythagoras.pyd
pause
Wichtige Voraussetzungen:
Schritt 5: Starte das Build-Script

Ergebnis: Das Modul build/lib/pythagoras.pyd wird erstellt und ist nun bereit zum Einsatz.

Füge Python-Wrapper und Testprogramm hinzu

Schritt 7: Füge pythagoras.py und main.py hinzu

Inhalt von pythagoras.py

"""
Python-Wrapper für das C-Modul 'pythagoras.c'

Verwende ctypes, um Funktionen aus dem .pyd-Modul zu importieren.
"""

import ctypes
import os

# Pfad zum Modul (auch in Python)
script_dir = os.path.dirname(os.path.abspath(__file__))
build_dir = os.path.join(script_dir, "build", "lib")

# Pfad zum C-Modul (für Windows)
pythagoras_path = os.path.join(build_dir, "pythagoras.pyd")

if not os.path.exists(pythagoras_path):
    raise FileNotFoundError(
        f"Modul nicht gefunden: {pythagoras_path}\n"
        "Bitte führe 'build.bat' aus, um das Modul zu kompilieren!"
    )

# Laden des C-Moduls über ctypes
try:
    pythagoras_lib = ctypes.CDLL(pythagoras_path)
except Exception as e:
    raise RuntimeError(f"Fehler beim Laden des C-Moduls: {e}")

# Funktionen aus C-Modul importieren
pythagoras_lib.aufstellen.argtypes = [ctypes.c_double, ctypes.c_double]
pythagoras_lib.aufstellen.restype = ctypes.c_double

pythagoras_lib.kontrolliere.argtypes = [ctypes.c_double, ctypes.c_double, ctypes.c_double]
pythagoras_lib.kontrolliere.restype = ctypes.c_int

pythagoras_lib.wurzel.argtypes = [ctypes.c_double, ctypes.c_double]
pythagoras_lib.wurzel.restype = ctypes.c_double

# Externe Funktion
def aufstellen(a, b):
    return pythagoras_lib.aufstellen(a, b)

def kontrolliere(a, b, c):
    return bool(pythagoras_lib.kontrolliere(a, b, c))

def wurzel(a, b):
    return pythagoras_lib.wurzel(a, b)

def ausgabe_pythagoras(a, b, c):
    pythagoras_lib.ausgabe_pythagoras(a, b, c)

# Exportiere Funktionen
__all__ = ["aufstellen", "kontrolliere", "wurzel", "ausgabe_pythagoras"]

# Test-Funktion
def test():
    print("Test erfolgreich!")
    a, b, c = 3.0, 4.0, 5.0
    print(f"a2 + b2 = {aufstellen(a, b)}")
    print(f"Ergebnis: {kontrolliere(a, b, c)}")
    print(f"c = {wurzel(a, b):.2f}")
    ausgabe_pythagoras(a, b, c)

Inhalt von main.py

"""
Testprogramm für das C-Modul 'pythagoras'
"""

import pythagoras

print("Test des C-Moduls 'pythagoras'")

a, b = 3.0, 4.0
c_squared = pythagoras.aufstellen(a, b)
print(f"Beispiel 1: a={a}, b={b} -> c2 = {c_squared}")

c = 5.0
is_valid = pythagoras.kontrolliere(a, b, c)
print(f"Beispiel 2: a={a}, b={b}, c={c}  -> Gleichung erfüllt? {is_valid}")

c_value = pythagoras.wurzel(a, b)
print(f"Beispiel 3: c = √({a}2 + {b}2) = {c_value:.2f}")

pythagoras.ausgabe_pythagoras(a, b, c)

print("\nTest erfolgreich!")

Ergebnis im Terminal

Test des C-Moduls 'pythagoras'
Beispiel 1: a=3.0, b=4.0 -> c2 = 25.0
Beispiel 2: a=3.0, b=4.0, c=5.0  -> Gleichung erfüllt? True
Beispiel 3: c = √(32 + 42) = 5.00
Pythagoras: 3.002 + 4.002 = 5.002
Test erfolgreich!

Installationsanleitung für MinGW (Windows)

  1. Gehe zu: https://www.msys2.org
  2. Downloade: msys2-x86_64-***** (Windows 64-Bit, letzte Version)
  3. Installiere das Paket mit dem Befehl:
  4. pacman -S mingw-w64-ucrt-x86_64-gcc
  5. Füge C:\msys64\ucrt64\bin zur Systemvariablen PATH hinzu.
  6. Überprüfe mit:
  7. gcc --version oder gcc -v
Fazit:
Wichtige Einschränkungen: