svaarala / duktape

Duktape - embeddable Javascript engine with a focus on portability and compact footprint
MIT License
5.96k stars 516 forks source link

Userdata type (pointer with prototype) #844

Open armornick opened 8 years ago

armornick commented 8 years ago

Would it be possible to create a pointer type which can be given a prototype (and a finalizer, of course)?

This would make it much easier to wrap C types directly instead of having to put the handle as a property of a normal Object. It would also be considerably safer since the properties of normal Objects can be modified.

svaarala commented 8 years ago

This has been discussed in other issues a few times - the basic limitation is that a pointer value is plain tagged type so there's no space for any prototype or finalizer pointer. A plain pointer value is literally just a type tag and a void * packed into either 8 bytes (for packed duk_tval) or 16 bytes (for a non-packed one, necessary on 64-bit platforms).

There are 16 unused bits in the 8-byte packed value format, though, which could be used to index some external table to provide a finalizer/prototype reference for example.

The pointer type could also be made heap allocated, but some applications do need the ability to store plain pointers memory efficiently so it's not really a solution.

Regarding objects being mutable - you can create properties that are non-writable and non-configurable. Ordinary Ecmascript code won't then be able to modify the property values or delete the properties. C code can bypass these limitations when using duk_def_prop() and the DUK_DEFPROP_FORCE flag, but other API calls will also refuse to modify/remove a non-writable and non-configurable property.

armornick commented 8 years ago

Fair enough. It's not a feature I absolutely need. It was just something I thought might be nice to have.