Skip to content

How to call JS function from C (or get exported value from JS_Eval)? #643

Answered by guyutongxue
guyutongxue asked this question in Q&A

You must be logged in to vote

Thank you @bnoordhuis and @saghul ! Here is a working example (sorry for using C++):

int main() {
  auto rt = JS_NewRuntime();
  auto ctx = JS_NewContext(rt);

  auto bytecode = JS_Eval(ctx, SOURCE.data(), SOURCE.size() - 1, "main.js",
                          JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY);
  JS_ResolveModule(ctx, bytecode);
  JS_EvalFunction(ctx, bytecode);
  auto def = static_cast<JSModuleDef*>(JS_VALUE_GET_PTR(bytecode));
  auto ns = JS_GetModuleNamespace(ctx, def);

  auto fn = JS_GetPropertyStr(ctx, ns, "hello");
  auto result = JS_Call(ctx, fn, JS_UNDEFINED, 0, nullptr);
  auto str = JS_ToCString(ctx, result);
  std::cout << str << std::endl;  // Expected "Hello"

Replies: 3 comments 5 replies

You must be logged in to vote
3 replies
@guyutongxue

@bnoordhuis

@saghul

You must be logged in to vote
1 reply
@saghul

Answer selected by guyutongxue

You must be logged in to vote
1 reply
@bnoordhuis

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
4 participants