Shiboken6: Python/C++ Bindings Helper
Shiboken6 is a core component of Qt for Python (PySide6), responsible for generating Python bindings for C++ libraries. It enables seamless, low-level interaction between Python and C++ objects, allowing Python to call C++ functions and access C++ data structures directly. It is currently at version 6.11.0 and is actively maintained, with updates released in conjunction with PySide6 and Qt releases.
Warnings
- breaking When migrating from PySide2/Qt5 to PySide6/Qt6, the Shiboken module name changed from `shiboken` to `shiboken6`. Direct imports or references to `shiboken` will result in `ModuleNotFoundError`.
- gotcha Using `shiboken6.wrapInstance` incorrectly, especially regarding memory ownership, can lead to memory leaks, double-frees, or application crashes. If `ownership` is not handled correctly, Python's garbage collector might attempt to delete a C++ object managed externally or prematurely.
- gotcha Shiboken6 is a low-level binding tool; it is not intended for general application development. Directly interacting with `shiboken6` beyond simple debugging with `getCppPointer` or specific C++/Python interoperability for custom extensions often indicates a deeper misunderstanding or an overly complex solution.
Install
-
pip install shiboken6
Imports
- wrapInstance
from shiboken6 import wrapInstance
- getCppPointer
from shiboken6 import getCppPointer
Quickstart
from shiboken6 import getCppPointer, wrapInstance
# PySide6 is required to run this example. Install with: pip install PySide6
from PySide6.QtCore import QObject
# Shiboken6 is typically used with PySide6 objects
obj = QObject()
obj.setObjectName("MyQObject")
# Get the underlying C++ pointer from a PySide6 object
cpp_ptr_long = getCppPointer(obj)
print(f"Python QObject: {obj}")
print(f"C++ pointer (long): {cpp_ptr_long:#x}")
print("\n--- Conceptual use of wrapInstance ---")
print("wrapInstance is used to convert a raw C++ pointer into a Python object.")
print("Example: `python_object = wrapInstance(raw_cpp_ptr, PySide6.ClassName, ownership=shiboken6.Ownership.CppOwnership)`")
print("It requires a valid C++ pointer (e.g., from an external C++ library call)")
print("and the expected PySide6 class type for correct wrapping. Careful memory")
print("management with `shiboken6.Ownership` is crucial to prevent crashes or leaks.")