Search code examples
v8embedded-v8

How do I assign a name to a v8::Object so that scripts can access it?


I'm currently trying to add scripting functionality to my C++ application by using v8. The goal is to process some data in buffers with JS and then return the result. I think I can generate an ArrayBuffer by using New with an appropriate BackingStore. The result would be a Local. I would now like to run scripts via v8::Script::Compile and v8::Script::Run. What would be the name of the ArrayBuffer - or how can I assign it a name so that it's accessible in the script? Do I need to make it a Globalif I need to run multiple scripts on the same ArrayBuffer?


Solution

  • If you want scripts to be able to access, say, my_array_buffer, then you'll have to install the ArrayBuffer as a property on the global object. See https://v8.dev/docs/embed for an introduction to embedding V8, and the additional examples linked from there. In short, it'll boil down to something like:

    global_object->Set(context, 
                       v8::String::NewFromUtf8(isolate, "my_array_buffer"), 
                       array_buffer);
    

    You don't need to store the ArrayBuffer in a Global for this to work.