Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7955417
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T03:42:28+00:00 2026-06-04T03:42:28+00:00

In Cython, say I have a C function that returns a large buffer allocated

  • 0

In Cython, say I have a C function that returns a large buffer allocated with malloc() and expected to be freed later with free().

Now I need to pass this buffer to Python as a (bytes) str object, which would acquire ownership of it, and call free() later when the str object goes away. Is this possible and how?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T03:42:30+00:00Added an answer on June 4, 2026 at 3:42 am

    Have a look at https://gist.github.com/1249305 for a implementation using numpy.

    If numpy is not an option then something like this could work, using a memoryview:

    from libc.stdlib cimport free
    cimport fn # in here is the c function with signature: char * char_ret(int n);
    
    cdef class BuffWrap:
        cdef long siz
        cdef char * _buf
        cdef char[:] arr
        def __cinit__(self,  long siz):
            self.siz = siz
            self._buf = fn.char_ret(siz) # storing the pointer so it can be freed
            self.arr = <char[:siz]>self._buf
        def __dealloc__(self):
            free(self._buf)
            self.arr = None
        # here some extras:
        def __str__(self):
            if self.siz<11:
                return 'BuffWrap: ' + str([ii for ii in self.arr])
            else:
                return ('BuffWrap: ' + str([self.arr[ii] for ii in range(5)])[0:-1] + ' ... '
                        + str([self.arr[ii] for ii in range(self.siz-5, self.siz)])[1:])
        def __getitem__(self, ind): 
            """ As example of magic method.  Implement rest of to get slicing
            http://docs.cython.org/src/userguide/special_methods.html#sequences-and-mappings
            """
            return self.arr[ind]
    

    Note the method __dealloc__ which will free the memory held by the pointer when all references to an instance of BuffWrap disappear and it gets garbage collected. This automatic deallocation is a good reason to wrap the whole thing in a class.

    I couldn’t figure out how one could use the returned pointer and use it for the buffer of, say, a bytearray. If someone knows, I’d be interested to see.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have some C source code and want to wrap it in Cython. Now,
I have the following code that is to be propperly converted to cython: from
I have a library written with cython that wraps a C library, and i'm
Now that I've successfully installed Cython on Windows 7, I try to compile some
Some standard C libraries that I want to access with Cython have a ton
Numpy has a basic pxd that declares its c interface to cython. Is there
I am reading cpython code for python 3k and I have noticed, that __missing__
I would like a function that can generate a pseudo-random sequence of values, but
In Cython, the usual raise keyword emits C code that contains a reference to
I have this Cython class: cdef class Sprite: def __init__(self, someargument): pass And I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.