Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

V8 modules exporting functions that call into c++

Tags:

v8

embedded-v8

I am looking to embed v8 and have a module available that exports a function that calls into c++ code. For example, let's assume I have something like the following in main.js:

import {foo} from 'FooBar';

foo();

Is there a way to have foo call into native c++ code? Looking for a push in the right direction, thanks in advance!

like image 952
Scarfone Avatar asked Nov 18 '25 23:11

Scarfone


1 Answers

If you're a very up-to-date version of V8, there a new subclass of Module called SyntheticModule which will let you create a virtual module where you can just directly set the exports.

https://cs.chromium.org/chromium/src/v8/include/v8.h?l=1406&rcl=d7cac7cb6a468995c1ec48611af283be8fb6c1ab

Local<Function> foo_func = ...;

Local<Module> module = Module::CreateSyntheticModule(
    isolate, name,
    {String::NewFromUtf8(isolate, "foo")},
    [](Local<Context> context, Local<Module> module) {
      module->SetSyntheticModuleExport(String::NewFromUtf8(isolate, "foo"), foo_func);
    });

// link `module` just like a normal source-text module.
like image 83
snek Avatar answered Nov 21 '25 08:11

snek