How to wrap a C pointer and length in a new-style buffer object in Cython?

后端 未结 3 1646
孤独总比滥情好
孤独总比滥情好 2021-01-05 00:29

I\'m writing a Python 2.7 extension module in Cython. How do I create a Python object implementing the new-style buffer interface that wraps a chunk of memory given

3条回答
  •  -上瘾入骨i
    2021-01-05 01:19

    As @RichardHansen correctly observes in his self-answer, what you want is a class that implements the buffer protocol, and has a suitable destructor that manages the memory.

    Cython actually provides a fairly lightweight class built into it in the form of cython.view.array so there's no need to create your own. It's actually documented in the page you linked but for the sake of providing a quick example that fits your case:

    # at the top of your file
    from cython.view cimport array
    
    # ...
    
    # after the call to dummy_function
    my_array = array(shape=(l,), itemsize=sizeof(char), format='b',  # or capital B depending on if it's signed
                     allocate_buffer=False)
    my_array.data = cstr
    my_array.callback_free_data = free
    
    cdef char[:] ret = my_array
    

    Just to draw attention to a couple of bits: allocate_buffer is set to False since you're allocating your own in cstr. Setting callback_free_data ensures that the standard library free function is used.

提交回复
热议问题