Skip to content

Commit

Permalink
Add helper for treating arbitrary function as member function
Browse files Browse the repository at this point in the history
  • Loading branch information
zcbenz committed Apr 12, 2024
1 parent e539c07 commit c4dbe5c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
23 changes: 23 additions & 0 deletions src/callback.h
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,29 @@ struct Type<T, typename std::enable_if<
}
};

// Helper mark a normal function as member function.
template<typename T>
struct MemberFunctionHolder {
T func;
};

template<typename T>
struct Type<MemberFunctionHolder<T>,
std::enable_if_t<
internal::IsFunctionConversionSupported<T>::value>> {
static constexpr const char* name = "Function";
static inline napi_status ToNode(napi_env env, MemberFunctionHolder<T> value,
napi_value* result) {
return internal::CreateNodeFunction(env, value.func, result,
HolderIsFirstArgument);
}
};

template<typename T>
inline MemberFunctionHolder<T> MemberFunction(T func) {
return MemberFunctionHolder<T>{func};
}

} // namespace ki

#endif // SRC_CALLBACK_H_
7 changes: 4 additions & 3 deletions src/callback_internal.h
Original file line number Diff line number Diff line change
Expand Up @@ -328,12 +328,13 @@ inline std::function<NodeCallbackSig> CreateNodeCallbackWithHolder(
// JavaScript arguments are automatically converted via Type<T>, as is
// the return value of the C++ function, if any.
template<typename T>
inline napi_status CreateNodeFunction(napi_env env, T func,
napi_value* result) {
inline napi_status CreateNodeFunction(napi_env env, T func, napi_value* result,
int flags = 0) {
using Factory = CallbackHolderFactory<T>;
using RunType = typename Factory::RunType;
using HolderT = typename Factory::HolderT;
auto holder = std::make_unique<HolderT>(Factory::Create(std::move(func)));
auto holder = std::make_unique<HolderT>(Factory::Create(std::move(func),
flags));
napi_value intermediate;
napi_status s = napi_create_function(env, nullptr, 0,
&ReturnToNode<RunType>::Invoke,
Expand Down

0 comments on commit c4dbe5c

Please sign in to comment.