V8 modules exporting functions that call into c++
Asked Answered
F

2

3

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!

Fountainhead answered 12/7, 2019 at 16:40 Comment(0)
G
4

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.
Goalkeeper answered 27/8, 2019 at 20:13 Comment(2)
Awesome! Exactly what I was looking for :D!Fountainhead
How to reference this module in js code?Fiddlestick
M
0

You can find various examples of this here: https://v8.dev/docs/embed

shell.cc is my goto example: https://github.com/v8/v8/blob/3a0f407d266ec6429a166cf2ec5132f6558d3a51/samples/shell.cc#L110-L114

Maeda answered 25/7, 2019 at 0:10 Comment(1)
It looks like those assign to the global object, instead of actually changing the module returned from the resolve callback you would use when instantiating a module. I am looking to specifically add a function to a module that calls into native code, if there is a way to do that?Fountainhead

© 2022 - 2024 — McMap. All rights reserved.