bellard / quickjs

Public repository of the QuickJS Javascript Engine.
https://bellard.org/quickjs
Other
8.55k stars 895 forks source link

Example of C class extending JS class #333

Open Sytten opened 4 months ago

Sytten commented 4 months ago

Hi!

Does someone have an example of a C class extending a JS class? Essentially the inverse of the Point example.

I am trying to re-create the node Buffer class in C and I want to extend the ArrayBuffer class.

Thanks

saghul commented 4 months ago

IIRC the Buffer class extends Uint8Array.

Anyway. I think you can get the prototype with JS_GetPrototype and then add your custom methods.

Sytten commented 4 months ago

Yes sorry Uint8Array.

That would work for the prototype, I probably also need something for the constructor to call the parent one.

saghul commented 4 months ago

Good point. I'm not sure QuickJS provider the necessary APIs to do that... @chqrlie ?

Sytten commented 4 months ago

I tried to use JS_GetClassProto with the class id of Uint8Array (12 at the moment), but it always returns an empty prototype for some reason. JS_GetPrototype on the globals does return something though. I was thinking of calling the prototype.constructor function if that exists? I have not tested it yet.

In reality I am writing that for the rust library rquickjs so I need to massage it a bit more but I didn't want to add complexity to the example.

saghul commented 4 months ago

Calling constructor on the prototype might work indeed!

chqrlie commented 4 months ago

@saghul Sorry, cannot comment right now, travelling 1200 km from the North pole with very little Internet coverage :)

Sytten commented 2 weeks ago

@chqrlie If you have time, still looking for guidance on it