[quickjs-devel] Re: JSValue as pointer

  • From: Saúl Ibarra Corretgé <s@xxxxxxxxxx>
  • To: quickjs-devel@xxxxxxxxxxxxx
  • Date: Wed, 21 Aug 2019 16:45:57 +0200

On 21/08/2019 16:30, Serghei Amelian (Redacted sender serghei for DMARC)
wrote:

I tried this approach, but it seems that JS_SetOpaque() / JS_GetOpaque() can 
be used only for clases, QuickJS crashes of I use JS_SetOpaque() to a 
function object created by JS_NewCFunction(). And JS_GetOpaque() needs anyway 
a class ID...


Is that a problem? Just create a dedicated class ID for your "capsules"
which just hold a pointer and use them to store any kind of pointer. You
could attach the JSValue for that function on the opaque type too.

As an example, here is the opaque data I'm using for implementing
timers:
https://github.com/saghul/quv/blob/c39d0803bf5b496252192c32af4fece24b3b4228/src/quv/timers.c#L39
it has the callback arguments attached to it too.


Cheers,

On Wed August 21 2019 17:26:47 Sac3bal Ibarra Corretgc3a9 wrote:
You can use JS_SetOpaque to attach a void* to a JSValue object. Maybe
this is what you are after?

Cheers,

On 21/08/2019 16:22, Serghei Amelian (Redacted sender serghei for DMARC)

wrote:
Hello,

JSValue can carry reliable a pointer? At this moment it seems that the
only method is to cast the pointer to an int64, but it looks a bit hacky
to me.

Example:

===========================

Convert the pointer to int64:

[...]

JSValue ptr[1] = { JS_NewInt64(ctx, reinterpret_cast<int64_t>(this)) };

JS_SetPropertyStr(ctx, global_obj, "print", JS_NewCFunctionData(ctx,
js_print, 1, 0, 1, ptr));

[...]

Convert back to pointer:

static JSValue js_print(JSContext *ctx, JSValue this_val, int argc,
JSValue *argv, int magic, JSValue *func_data)

{

ICEJsEngine *jse;

JS_ToIndex(ctx, (uint64_t*)&jse, *func_data);

[...]

}

===========================

Or maybe my approach is not right?

Thanks.

--

Serghei





-- 
Saúl

Other related posts: