Turn objects into unique integers

Issue #87 resolved
Armin Rigo
created an issue

Take the "best" way to encode Python objects as numbers and back, and put it as convenience methods on ffi. For example,

    with ffi.unique_integer(x) as i:
         y = ffi.get_object_from_integer(i)

The with statement is used to know exactly for how long the integer i is supposed to remain valid. Something like that anyway; the API may need adaptations to also support non-with-statement approaches.

Comments (7)

  1. Armin Rigo reporter

    Just to be clear, this would be useful in particular for callbacks, where the C tradition is to pass a void * pointer along. To do this we'd get a unique integer from a Python object and cast it to (or possibly directly get) an opaque void *, which can later be converted to a Python object again.

  2. Simon Sapin

    I just thought of crazy hacks to get the object back from its id(), but that only work on CPython where it’s the address in memory. Forget that part, but the part about keeping the object alive is still relevant.

    So, I suppose this would work with a gloabl dict of these unique integers as keys, and either the objects themselves (strong references) or weakrefs as values?

  3. Armin Rigo reporter

    Yes, although it can be a list instead of a dict, if we return small integers.

    We thought about another API more similar to the rest of cffi: ptr_handle = ffi.new_handle(x), returning a regular <cdata "void *">. To get back the object x from any cdata that contains the same void * value we use x = ffi.from_handle(ptr). The rules about being kept alive are the same as with ffi.new(): the handle is valid (and x is kept alive) as long as the original ptr_handle object exists.

  4. Log in to comment