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
Discussion options

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: 2 comments 4 replies

Comment options

You must be logged in to vote
3 replies
@guyutongxue
Comment options

@bnoordhuis
Comment options

@saghul
Comment options

Comment options

You must be logged in to vote
1 reply
@saghul
Comment options

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