Safety of C++ object tracking via Integer IDs
mainTo prevent use-after-free errors and manage memory safely when interacting with JavaScript, PyMiniRacer avoids passing raw C++ pointers to the JavaScript environment. Instead, it uses Integer IDs.
The Workflow:
- The C++ side allocates an object and stores it in a map (e.g.,
std::unordered_map<uint64_t, std::shared_ptr<T>>). - C++ provides only the numeric
uint64_tID to JavaScript. - When JavaScript calls back into C++, the ID is used to look up the pointer in the map.
- The C++ side validates that the ID is still present in the map before using the pointer.
This allows the C++ side to be the authoritative owner of object lifecycles. If an object is deleted, the ID becomes invalid, and subsequent attempts by JavaScript to use that ID can be safely ignored or handled as errors.