From 1174e544b0283bd30962d0a6a528af0aca43367c Mon Sep 17 00:00:00 2001 From: Brian Potchik Date: Thu, 17 Aug 2023 17:47:55 -0400 Subject: Ensure consistent lifetimes for UI-accessible BinaryView instances in Python. --- python/binaryview.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) (limited to 'python/binaryview.py') diff --git a/python/binaryview.py b/python/binaryview.py index 6ba8d33f..4b1ca035 100644 --- a/python/binaryview.py +++ b/python/binaryview.py @@ -1911,6 +1911,30 @@ class BinaryView: registered_view_type = None _associated_data = {} _registered_instances = [] + _cached_instances = {} + + @classmethod + def _cache_insert(cls, instance): + key = ctypes.addressof(instance.handle.contents) + if key not in cls._cached_instances: + cls._cached_instances[ctypes.addressof(instance.handle.contents)] = instance + + @classmethod + def _cache_remove(cls, handle): + key = ctypes.addressof(handle.contents) + if key in cls._cached_instances: + cls._cached_instances.pop(key) + + @classmethod + def _cache_contains(cls, handle): + return ctypes.addressof(handle.contents) in cls._cached_instances + + def __new__(cls, file_metadata=None, parent_view=None, handle=None): + if handle: + key = ctypes.addressof(handle.contents) + if key in cls._cached_instances: + return cls._cached_instances[key] + return super().__new__(cls) def __init__( self, file_metadata: Optional['filemetadata.FileMetadata'] = None, parent_view: Optional['BinaryView'] = None, @@ -1918,6 +1942,8 @@ class BinaryView: ): if handle is not None: _handle = handle + if self.__class__._cache_contains(handle): + return if file_metadata is None: self._file = filemetadata.FileMetadata(handle=core.BNGetFileForView(handle)) else: -- cgit v1.3.1