Search code examples
v8spidermonkeyduktape

Keeping UINT64 values in V8


I'm looking to integrate a scripting engine in my C/C++ program. Currently, I am looking at Google V8.

How do I efficiently handle 64 bit values in V8? My C/C++ program uses 64 bit values extensivly for keeping handlers/pointers. I don't want them separatelly allocated on the heap. There appears to be a V8::External value type. Can I assign it to a Javascript variable and use it as a value type?

function foo() {

   var a = MyNativeFunctionReturningAnUnsigned64BitValue();

   var b = a; // Hopefully, b is a stack allocated value capable of
              // keeping a 64 bit pointer or some other uint64 structure.

   MyNativeFunctionThatAcceptsAnUnsigned64BitValue(b);

}

If it is not possible in V8, how about SpiderMonkey? I know that Duktape (Javascript engine) has a non Ecmascript standard 64 bit value type (stack allocated) to host pointers, but I would assume that other engines also wants to keep track of external pointers from within their objects.


Solution

  • No it's not possible and I'm afraid duktape could be violating the spec unless it took some great pains to ensure it's not observable.

    You can store pointers in objects so to store 64-bit ints directly on an object you need pointers to have the same size:

    Local<FunctionTemplate> function_template = FunctionTemplate::New(isolate);
    // Instances of this function have room for 1 internal field
    function_template->InstanceTemplate()->SetInternalFieldCount(1);
    
    Local<Object> object = function_template->GetFunction()->NewInstance();
    static_assert(sizeof(void*) == sizeof(uint64_t));
    uint64_t integer = 1;
    object->SetAlignedPointerInInternalField(0, reinterpret_cast<void*>(integer));
    uint64_t result = reinterpret_cast<uint64_t>(object->GetAlignedPointerInInternalField(0));
    

    This is of course far from being efficient.