[Cython] automatically raise MemoryError on exceptional C return values

Stefan Behnel stefan_ml at behnel.de
Tue Aug 7 11:53:40 CEST 2012


Hi,

given how ubiquitous manual memory management is in C, I think it would be
nice to let Cython generate the exception raising also for C, not only for
C++. The difference is this:

  cdef extern from "...":
      char* make_new_buffer() except NULL as MemoryError
      int append_to_buffer(char* buffer, char* value) \
                                     except -1 as MemoryError

  c_buffer = make_new_buffer()           # raises MemoryError on NULL
  append_to_buffer(c_buffer, "testdata") # raises MemoryError on -1
  append_to_buffer(c_buffer, "moredata") # raises MemoryError on -1

versus this:

   cdef extern from "...":
       char* make_new_buffer()
       int append_to_buffer(char* buffer, char* value)

   c_buffer = make_new_buffer()
   if c_buffer is NULL:
       raise MemoryError()
   if append_to_buffer(c_buffer, "testdata") == -1:
       raise MemoryError()
   if append_to_buffer(c_buffer, "moredata") == -1:
       raise MemoryError()

I don't think it's necessary to support this for anything but MemoryError,
since you'd normally want a formatted error message for everything else.

Alternative colours for the bike shed:

    char* make_new_buffer() except NULL raise MemoryError

    char* make_new_buffer() raise MemoryError for NULL

    char* make_new_buffer() raise MemoryError from NULL

What do you think?

Stefan


More information about the cython-devel mailing list