2

In other words, is it safe for C code, given a reference to Python object to assume that, provided it called Py_INCREF on it, the pointer will not become invalid?

If you are wondering how this may happen: for example, Java GC is allowed to relocate objects in memory to prevent memory fragmentation. This will, however, preclude you from using "raw" pointers to Java objects, since you may get a garbage reference.


Somewhat related: how can C code determine that Python object was garbage-collected, if it doesn't want to increase reference count (for example, if implementing WeakKeyDictionary)?

wvxvw
  • 8,089
  • 10
  • 32
  • 61
  • 1
    https://stackoverflow.com/questions/35300396/does-cpythons-garbage-collection-do-compaction – NPE Feb 25 '18 at 18:01
  • 1
    I'd ask two separate questions, the first question you're asking is answered by @NPE's link (**duplicate**) -- the second is answered by using the [`WeakRef` api](https://docs.python.org/3/c-api/weakref.html) -- a possible dupe target for that is [here](https://stackoverflow.com/q/2993393/812183) – anthony sottile Feb 25 '18 at 18:09
  • 2
    Possible duplicate of [Does CPython's garbage collection do compaction?](https://stackoverflow.com/questions/35300396/does-cpythons-garbage-collection-do-compaction) – anthony sottile Feb 25 '18 at 18:09
  • 1
    Per @AnthonySottile: Possible duplicate of [Python - how to check if weak reference is still available](https://stackoverflow.com/questions/2993393/python-how-to-check-if-weak-reference-is-still-available) – Davis Herring Feb 25 '18 at 18:14
  • @NPE and @ here thanks. I didn't know it's also called compaction, that's why I didn't find that. Good to know. – wvxvw Feb 25 '18 at 20:25

0 Answers0