quickjs icon indicating copy to clipboard operation
quickjs copied to clipboard

Example of C class extending JS class

Open Sytten opened this issue 1 year ago • 6 comments

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

Sytten avatar Jul 19 '24 16:07 Sytten

IIRC the Buffer class extends Uint8Array.

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

saghul avatar Jul 19 '24 17:07 saghul

Yes sorry Uint8Array.

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

Sytten avatar Jul 19 '24 18:07 Sytten

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

saghul avatar Jul 22 '24 14:07 saghul

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.

Sytten avatar Jul 22 '24 16:07 Sytten

Calling constructor on the prototype might work indeed!

saghul avatar Jul 22 '24 17:07 saghul

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

chqrlie avatar Jul 22 '24 22:07 chqrlie

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

Sytten avatar Nov 05 '24 18:11 Sytten

I guess no resolution on this one

Sytten avatar May 24 '25 12:05 Sytten

I though that using JS_GetClassProto() and then accessing the "constructor" property solved the issue.

bellard avatar May 24 '25 13:05 bellard

The prototype can get you the parent prototype but calling the constructor to create a subclass is really not self evident. Same idea to make instanceof work correctly. Anyway rquickjs moved to quickjs-ng so I will check with them.

Sytten avatar May 24 '25 17:05 Sytten