diff --git a/local-tool/server/scripts/kneron_bridge.py b/local-tool/server/scripts/kneron_bridge.py index 0e2120b..4f4bd95 100644 --- a/local-tool/server/scripts/kneron_bridge.py +++ b/local-tool/server/scripts/kneron_bridge.py @@ -1112,5 +1112,26 @@ def main(): _respond({"error": str(e)}) +def _cleanup(): + """Explicitly disconnect and clear _device_group before Python GC runs. + + KneronPLUS SDK's DeviceGroup.__del__ calls kp_disconnect_devices on a + native handle that may already be freed when the interpreter is shutting + down, causing 'OSError: access violation reading 0x00...'. By doing a + clean disconnect + setting the global to None here, __del__ becomes a + no-op (None has no __del__). + """ + global _device_group + if _device_group is not None: + try: + kp.core.disconnect_devices(_device_group) + except Exception: + pass + _device_group = None + + if __name__ == "__main__": + import atexit + atexit.register(_cleanup) main() + _cleanup() # also call synchronously in case atexit doesn't fire