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.
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.
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.Fehlerprüfung,en Klassen und pytest als Testverfahren, hinzugefügt worden. Viel Erfolg!
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
Erstelle ein neues Projekt in Visual Studio 2022 und füge die C-Datei hinzu:
pythagoras_projectC:\pythagoras_projectpythagoras.cpythagoras.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);
}
.c führt zu C-Kompilierung, .cpp zu C++./TC für C, /TP für C++).__cdecl) ist wichtig hier wird standardmäßig __cdecl verwendet.Visual Studio 2022 bietet keine direkte Option, um ein .pyd-Modul zu erstellen. Daher muss das Modul über ein Build-Script kompiliert werden.
build.bat im Projektverzeichnis.gcc.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
gcc muss in der Systemvariablen PATH vorhanden sein.gcc -v oder gcc --version müssen funktionieren.cd C:\pythagoras_project
build.bat
Ergebnis: Das Modul build/lib/pythagoras.pyd wird erstellt und ist nun bereit zum Einsatz.
pythagoras.py und main.pypythagoras.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)
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!")
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!
msys2-x86_64-***** (Windows 64-Bit, letzte Version)pacman -S mingw-w64-ucrt-x86_64-gcc
C:\msys64\ucrt64\bin zur Systemvariablen PATH hinzu.gcc --version oder gcc -v
ctypesmain.py)pythagoras.pyPython.h) ist nicht in diesem Beispiel enthalten sie wäre nötig, um echte Python-Objekte zu verwenden.