Skip to content

Commit

Permalink
Escape the result when converted function returns napi_value
Browse files Browse the repository at this point in the history
  • Loading branch information
zcbenz committed Jul 5, 2024
1 parent df8dd6a commit a063c65
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/callback_internal.h
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,34 @@ struct V8FunctionInvoker<ReturnType(ArgTypes...)> {
}
};

template<typename... ArgTypes>
struct V8FunctionInvoker<napi_value(ArgTypes...)> {
static napi_value Go(napi_env env, Persistent* handle, ArgTypes&&... raw) {
EscapableHandleScope handle_scope(env);
napi_value func = handle->Value();
if (!func) {
ThrowError(env, "The function has been garbage collected");
return nullptr;
}
std::vector<napi_value> args = {
ToNode(env, std::forward<ArgTypes>(raw))...
};
napi_value result;
napi_status s = napi_make_callback(env, nullptr, func, func, args.size(),
args.empty() ? nullptr: &args.front(),
&result);
if (s == napi_ok) {
return handle_scope.Escape(result);
}
if (s == napi_pending_exception) {
napi_value fatal_exception;
napi_get_and_clear_last_exception(env, &fatal_exception);
napi_fatal_exception(env, fatal_exception);
}
return nullptr;
}
};

} // namespace internal

} // namespace ki
Expand Down
31 changes: 31 additions & 0 deletions src/napi_util.h
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,37 @@ class HandleScope {
napi_handle_scope scope_;
};

class EscapableHandleScope {
public:
explicit EscapableHandleScope(napi_env env) : env_(env) {
napi_status s = napi_open_escapable_handle_scope(env, &scope_);
assert(s == napi_ok);
}

~EscapableHandleScope() {
napi_status s = napi_close_escapable_handle_scope(env_, scope_);
assert(s == napi_ok);
}

napi_value Escape(napi_value handle) {
napi_value result = nullptr;
napi_escape_handle(env_, scope_, handle, &result);
return result;
}

EscapableHandleScope& operator=(const EscapableHandleScope&) = delete;
EscapableHandleScope(const EscapableHandleScope&) = delete;

void* operator new(size_t) = delete;
void* operator new[] (size_t) = delete;
void operator delete(void*) = delete;
void operator delete[] (void*) = delete;

private:
napi_env env_;
napi_escapable_handle_scope scope_;
};

} // namespace ki

#endif // SRC_NAPI_UTIL_H_

0 comments on commit a063c65

Please sign in to comment.