Zadania

  1. raylib_ctypes.py - integracja biblioteki Raylib z Pythonem wykorzystując ctypes

  2. raylib_lib.py - integracja biblioteki Raylib z Pythonem wykorzystując mechanizm rozszerzeń

Biblioteki Pythonowe w języku C (mechanizm rozszerzeń)

Tworzenie biblioteki Pythona w C

  1. Stwórz wirtualne środowisko: python -m venv venv, a następnie je uruchom: . venv/bin/activate

  2. Stwórz implementację biblioteki:

    #define PY_SSIZE_T_CLEAN
    #include <Python.h>
    
    static PyObject* hello(PyObject *self, PyObject *args)
    {
            (void)self;
            (void)args;
            PyErr_SetString(PyExc_NotImplementedError, "C function hello has not been implemented yet");
            return NULL;
    }
    
    static PyMethodDef hello_methods[] = {
            { "hello", hello, METH_VARARGS, "Prints hello" },
            { NULL, NULL, 0, NULL }, /* end marker */
    };
    
    static PyModuleDef hello_module = {
            PyModuleDef_HEAD_INIT,
            "hello",
            NULL, /* module documentation */
            -1,
            hello_methods,
    };
    
    PyMODINIT_FUNC PyInit_hello(void)
    {
            return PyModule_Create(&hello_module);
    }
  3. Stwórz konfigurację projektu:

    [project]
    name = "hello"
    version = "0.1.0"
    
    [build-system]
    requires = ["setuptools"]
    build-backend = "setuptools.build_meta"
    
    [tool.setuptools]
    ext-modules = [
      {name = "hello", sources = ["hello.c"]}
    ]
  4. Zainstaluj zależności pozwalające na zbudowanie projektu: pip install --upgrade setuptools[core] build

  5. Zbuduj projekt: python -m build

  6. Zainstaluj zbudowany projekt: pip install ./dist/hello-0.1.0.tar.gz

  7. Przetestuj poprawne zainstalowanie projektu: python3 -c "import hello; hello.hello()"

Aby kolejny raz zbudować projekt należy powtórzyć następujące kroki:

  1. Zbuduj projekt: python -m build

  2. Zainstaluj zbudowany projekt: pip install ./dist/hello-0.1.0.tar.gz

  3. Przetestuj poprawne zainstalowanie projektu: python3 -c "import hello; hello.hello()"

Ładowanie bibliotek C z Pythona (FFI)