Skip to content

Commit fb8e365

Browse files
committed
gc patches with c pointers
1 parent 4154714 commit fb8e365

File tree

2 files changed

+25
-5
lines changed

2 files changed

+25
-5
lines changed

src/pointers/c_pointer.py

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,9 @@ def __rich__(self):
209209
return (
210210
f"<[green]void[/green] pointer to [cyan]{hex(self.address)}[/cyan]>" # noqa
211211
)
212+
213+
def __del__(self):
214+
pass
212215

213216

214217
class TypedCPointer(_BaseCPointer[T], Generic[T]):
@@ -219,11 +222,13 @@ def __init__(
219222
address: int,
220223
data_type: Type[T],
221224
size: int,
222-
alternate_method: bool = True
225+
alternate_method: bool = True,
226+
decref: bool = True
223227
):
224228
self._alt = alternate_method
225229
super().__init__(address, size)
226230
self._type = data_type
231+
self._decref = decref
227232

228233
@property
229234
def _as_parameter_(self) -> "ctypes.pointer[ctypes._CData]":
@@ -255,7 +260,7 @@ def __rich__(self):
255260
return f"<[green]typed c[/green] pointer to [cyan]{hex(self.address)}[/cyan]>" # noqa
256261

257262
def __del__(self):
258-
if self.type is not str:
263+
if (self.type is not str) and (self._decref):
259264
super().__del__()
260265
remove_ref(~self)
261266

@@ -264,7 +269,12 @@ def __del__(self):
264269

265270
def cast(ptr: VoidPointer, data_type: Type[T]) -> TypedCPointer[T]:
266271
"""Cast a void pointer to a typed pointer."""
267-
return TypedCPointer(ptr.address, data_type, ptr.size)
272+
return TypedCPointer(
273+
ptr.address,
274+
data_type,
275+
ptr.size,
276+
decref = False
277+
)
268278

269279

270280
def to_c_ptr(data: T) -> TypedCPointer[T]:

tests/test_binding.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
11
from pointers import (
22
to_c_ptr,
3-
TypedCPointer,
43
StructPointer,
54
localeconv,
6-
frexp,
75
div,
86
strlen,
97
c_malloc,
@@ -24,3 +22,15 @@ def test_bindings():
2422
r = strlen("test")
2523
assert r == 4
2624
assert type(r) is int
25+
26+
def test_to_c_ptr():
27+
a = to_c_ptr('test')
28+
assert a.type is str
29+
assert ~a == 'test'
30+
31+
def test_strings():
32+
mem = c_malloc(2)
33+
sprintf(mem, "%s", "a") # testing format strings
34+
ptr = cast(mem, bytes)
35+
assert ~ptr == b"a"
36+
c_free(mem)

0 commit comments

Comments
 (0)