Skip to content

Commit 0ba130d

Browse files
Merge pull request #460 from barakugav/ffi-ptr
Add `as_ffi_ptr` to NDArray
2 parents 1a176c5 + 1e87fb9 commit 0ba130d

File tree

3 files changed

+26
-0
lines changed

3 files changed

+26
-0
lines changed

src/blosc2/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -328,6 +328,7 @@ class Tuner(Enum):
328328
arctan,
329329
arctan2,
330330
arctanh,
331+
array_from_ffi_ptr,
331332
conj,
332333
contains,
333334
cos,

src/blosc2/blosc2_ext.pyx

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2615,6 +2615,9 @@ cdef class NDArray:
26152615
if self.array.shape[0] == 1 and self.ndim == 1:
26162616
self.array.ndim = 0
26172617

2618+
def as_ffi_ptr(self):
2619+
return PyCapsule_New(self.array, <char *> "b2nd_array_t*", NULL)
2620+
26182621
cdef udf_udata *_fill_udf_udata(self, func_id, inputs_id):
26192622
cdef udf_udata *udata = <udf_udata *> malloc(sizeof(udf_udata))
26202623
udata.py_func = <char *> malloc(strlen(func_id) + 1)
@@ -2901,6 +2904,10 @@ def asarray(ndarray, chunks, blocks, **kwargs):
29012904

29022905
return ndarray
29032906

2907+
def array_from_ffi_ptr(array_ptr):
2908+
array = <b2nd_array_t *> PyCapsule_GetPointer(array_ptr, <char *> "b2nd_array_t*")
2909+
return blosc2.NDArray(_schunk=PyCapsule_New(array.sc, <char *> "blosc2_schunk*", NULL),
2910+
_array=array_ptr)
29042911

29052912
def ndarray_from_cframe(cframe, copy=False):
29062913
cdef Py_buffer buf

src/blosc2/ndarray.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2169,6 +2169,24 @@ def sort(self, order: str | list[str] | None = None, **kwargs: Any) -> NDArray:
21692169
"""
21702170
return sort(self, order, **kwargs)
21712171

2172+
def as_ffi_ptr(self):
2173+
"""Returns the pointer to the raw FFI blosc2::b2nd_array_t object.
2174+
2175+
This function is useful for passing the array to C functions.
2176+
"""
2177+
return super().as_ffi_ptr()
2178+
2179+
2180+
def array_from_ffi_ptr(array_ptr) -> NDArray:
2181+
"""
2182+
Create an NDArray from a raw FFI pointer.
2183+
2184+
This function is useful for passing arrays across FFI boundaries.
2185+
This function move the ownership of the underlying `b2nd_array_t*` object to the new NDArray, and it will be freed
2186+
when the object is destroyed.
2187+
"""
2188+
return blosc2_ext.array_from_ffi_ptr(array_ptr)
2189+
21722190

21732191
def sin(ndarr: NDArray | NDField | blosc2.C2Array | blosc2.LazyExpr, /) -> blosc2.LazyExpr:
21742192
"""

0 commit comments

Comments
 (0)