Open svaarala opened 8 years ago
LoL, I didn't know this was the way to associate user data with a context / get it back!
To be precise the userdata is associated with the heap: the allocation functions, fatal error handler, and several configurable macros like heap pointer compression.
Hum. Right now I'm not overriding the allocators, but I want to use the userdata to store a pointer to the structure that has the pointer to the main Duktape context. Would I be doing something wrong?
That's fine, if your allocators won't need the userdata (and they don't if they're the default ones) you can use it for whatever purpose.
Choosing the "right" number of userdata pointers is actually a bit difficult to get right: there could be separate userdata values for allocator functions, fatal error handling, pointer compression, etc. The downside is that one would need to register a lot of userdata values which would normally not be needed. On the other hand, it's somewhat non-modular that the userdata is shared between, say, an allocation provider and a fatal error handler. That doesn't seem to cause a lot of implementation issues (the allocators etc are relatively simple in the end) so the shared userdata is the current approach.
Plus it's easy enough to put the relevant data into a struct. Logically the allocator functions, fatal error handler, etc. are all tied to the lifetime of the same heap so the shared pointer is most intuitive, I think.
The theoretical problem is that if I want to write an allocator which needs a udata
, it can't be used modularly in any Duktape application because the udata
may also be needed by the fatal error handler. Putting the values into a struct requires changes to the allocator so it's no longer easy to distribute as is (it's also slower to look up through a struct).
This hasn't been a problem in practice AFAIK, but it's still nagging me a bit.
Currently
duk_get_memory_functions()
is needed to get the heap userdata, maybe a direct call likevoid *duk_get_heap_udata(duk_context *ctx)
.On a related note,
duk_get_memory_functions()
is a bit of an odd call. Having an API call to get all heap information (including the fatal handler) would be more consistent as it would then match the heap initialization call.