Skip to content

Commit 302fbbb

Browse files
committed
context: automatically destroy context
When the last reference on the struct ly_ctx pointer is lost, make sure that ly_ctx_destroy is called. Obviously, only do that if the pointer was allocated by us. If the pointer was borrowed, do not call ly_ctx_destroy. Signed-off-by: Robin Jarry <robin.jarry@6wind.com>
1 parent d164c08 commit 302fbbb

File tree

1 file changed

+6
-2
lines changed

1 file changed

+6
-2
lines changed

libyang/context.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,10 @@ def __init__(
3434
if disable_searchdir_cwd:
3535
options |= lib.LY_CTX_DISABLE_SEARCHDIR_CWD
3636

37-
self.cdata = lib.ly_ctx_new(ffi.NULL, options)
37+
self.cdata = ffi.gc(
38+
lib.ly_ctx_new(ffi.NULL, options),
39+
lambda ctx: lib.ly_ctx_destroy(ctx, ffi.NULL),
40+
)
3841
if not self.cdata:
3942
raise self.error("cannot create context")
4043

@@ -61,7 +64,8 @@ def _ctx(self):
6164

6265
def destroy(self):
6366
if self.cdata is not None:
64-
lib.ly_ctx_destroy(self.cdata, ffi.NULL)
67+
if hasattr(ffi, "release"):
68+
ffi.release(self.cdata) # causes ly_ctx_destroy to be called
6569
self.cdata = None
6670

6771
def __enter__(self):

0 commit comments

Comments
 (0)