Turn objects into unique integers

Armin Rigo avatarArmin 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

    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. Alex Gaynor

    id() doesn't work because there's no way to reverse the value, the point of this is that it's reversable and keeps the object alive automatically.

  3. 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?

  4. Armin Rigo

    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.

  5. Log in to comment
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.