Skip to content

Commit

Permalink
allow regular class member objects to be accessed w/o copying
Browse files Browse the repository at this point in the history
  • Loading branch information
mmomtchev committed Dec 22, 2023
1 parent dd9ab05 commit 72751d8
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 5 deletions.
12 changes: 9 additions & 3 deletions include/noobject.h
Original file line number Diff line number Diff line change
Expand Up @@ -624,10 +624,16 @@ template <typename T, const ReturnAttribute &RETATTR> class ToJS {
T *object;

public:
inline explicit ToJS(Napi::Env env, T val) : env_(env) {
inline explicit ToJS(Napi::Env env, T &val) : env_(env) {
if constexpr (std::is_object_v<T> && !std::is_pod_v<T>) {
// C++ returned regular stack-allocated object, import to JS by copying to the heap
object = new T(val);
// C++ returned regular object
if constexpr (RETATTR.isNested()) {
// This is a nested object from a getter (for a class member object), return a nested reference
object = &val;
} else {
// This is a stack-allocated object, copy it to the heap
object = new T(val);
}
} else {
static_assert(!std::is_same<T, T>(), "Type does not have a ToJS typemap");
}
Expand Down
2 changes: 1 addition & 1 deletion include/nostl.h
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ template <typename M, typename T, const ReturnAttribute &RETATTR> class ToJSMap
inline explicit ToJSMap(Napi::Env env, M val) : env_(env), val_(val) {}
inline Napi::Value Get() {
Napi::Object object = Napi::Object::New(env_);
for (auto const &prop : val_) {
for (auto &prop : val_) {
object.Set(Napi::String::New(env_, prop.first), ToJS<T, RETATTR>(env_, prop.second).Get());
}
return object;
Expand Down
2 changes: 1 addition & 1 deletion test/tests/nested.cc
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ NOBIND_MODULE(nested, m) {
m.def<DateTime>("DateTime")
.cons<Time>()
.cons<unsigned long>()
// Getters of object members automatically return nested references
// Getters of object members references automatically return nested references
.def<&DateTime::time>("time")
// Explicitly return a nested reference
.def<&DateTime::operator Time &, Nobind::ReturnNested>("get");
Expand Down

0 comments on commit 72751d8

Please sign in to comment.