How to wrap a c library function that returns raw image data efficiently?

24 views
Skip to first unread message

Vivek Kumar

unread,
Mar 21, 2024, 1:54:37 PMMar 21
to cython-users
Hi, I am working on wrapping an existing C library using cython. The library has an API to get the get the raw image data 
bool getImage(unsigned char* image)
How can I wrap it in a such that it returns a python array which uses the same memory that was allocated in C? Following is my pyx code
def get_image(int width, int height):
 
    cdef float* buffer =
<float*>PyMem_Malloc(width * height * sizeof(unsigned char))

    cdef bint success = getImage(buffer)
   
    return bool(success), buffer // Doesn't compile since not a pyobj

da-woods

unread,
Mar 21, 2024, 5:42:27 PMMar 21
to cython...@googlegroups.com
I'd suggest something like:

def get_image(int width, int height):
    cdef float[:,::1] mview
    arr = np.empty((width, height), dtype=np.float32)
    mview = arr
    success = getImage(&mview[0,0])
    if success:
        return arr
    else:
        return None

I'm allocating memory as a Numpy array (since that's easy to return) and using a memoryview to get a pointer to the data.

Note that I've returned "None or a numpy array" rather than a tuple of success and array, since this seems like a more natural Python interface.
--

---
You received this message because you are subscribed to the Google Groups "cython-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cython-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/cython-users/a8cf51d8-76d9-4e78-85d5-b92475ae7a25n%40googlegroups.com.


Reply all
Reply to author
Forward
0 new messages