Skip to content

Commit 92853c5

Browse files
committed
n-api: enable napi_wrap() to work with any object
Previously, napi_wrap() would only work with objects created from a constructor returned by napi_define_class(). While the N-API team was aware of this limitation, it was not clearly documented and is likely to cause confusion anyway. It's much simpler if addons are allowed to use any JS object. Also, the specific behavior of the limitation is difficult to reimplement on other VMs that work differently from V8. V8 requires object internal fields to be declared on the object prototype (which napi_define_class() used to do). Since it's too late to modify the object prototype by the time napi_wrap() is called, napi_wrap() now inserts a new object (with the internal field) into the supplied object's prototype chain. Then it can be retrieved from there later by napi_unwrap(). This change also includes improvements to the documentation for napi_create_external(), partly to explain how it is different from napi_wrap().
1 parent 3b12a8d commit 92853c5

File tree

4 files changed

+85
-30
lines changed

4 files changed

+85
-30
lines changed

doc/api/n-api.md

Lines changed: 29 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1059,20 +1059,24 @@ napi_status napi_create_external(napi_env env,
10591059
```
10601060

10611061
- `[in] env`: The environment that the API is invoked under.
1062-
- `[in] data`: Raw pointer to the external data being wrapped.
1063-
- `[in] finalize_cb`: Optional callback to call when the wrapped object
1062+
- `[in] data`: Raw pointer to the external data.
1063+
- `[in] finalize_cb`: Optional callback to call when the external value
10641064
is being collected.
10651065
- `[in] finalize_hint`: Optional hint to pass to the finalize callback
10661066
during collection.
1067-
- `[out] result`: A `napi_value` representing an external object.
1067+
- `[out] result`: A `napi_value` representing an external value.
10681068

10691069
Returns `napi_ok` if the API succeeded.
10701070

1071-
This API allocates a JavaScript object with external data attached to it.
1072-
This is used to wrap native objects and project them into JavaScript.
1073-
The API allows the caller to pass in a finalize callback, in case the
1074-
underlying native resource needs to be cleaned up when the wrapper
1075-
JavaScript object gets collected.
1071+
This API allocates a JavaScript value with external data attached to it. This
1072+
is used to pass external data through JavaScript code, so it can be retrieved
1073+
later by native code. The API allows the caller to pass in a finalize callback,
1074+
in case the underlying native resource needs to be cleaned up when the external
1075+
JavaScript value gets collected.
1076+
1077+
Note: The created value is not an object, and therefore does not support
1078+
additional properties. It is considered a distinct value type: calling
1079+
`napi_typeof()` with an external value yields `napi_external`.
10761080

10771081
#### napi_create_external_arraybuffer
10781082
<!-- YAML
@@ -1457,8 +1461,8 @@ Boolean.
14571461
Returns `napi_ok` if the API succeeded. If a non-boolean `napi_value` is
14581462
passed in it returns `napi_boolean_expected`.
14591463
1460-
This API returns C boolean primitive equivalent of the given JavaScript
1461-
Boolea
1464+
This API returns the C boolean primitive equivalent of the given JavaScript
1465+
Boolean.
14621466
14631467
#### *napi_get_value_double*
14641468
<!-- YAML
@@ -1493,14 +1497,14 @@ napi_status napi_get_value_external(napi_env env,
14931497
```
14941498
14951499
- `[in] env`: The environment that the API is invoked under.
1496-
- `[in] value`: `napi_value` representing JavaScript External value.
1497-
- `[out] result`: Pointer to the data wrapped by the JavaScript External value.
1500+
- `[in] value`: `napi_value` representing JavaScript external value.
1501+
- `[out] result`: Pointer to the data wrapped by the JavaScript external value.
14981502
14991503
Returns `napi_ok` if the API succeeded. If a non-external `napi_value` is
15001504
passed in it returns `napi_invalid_arg`.
15011505
1502-
This API returns the pointer to the data wrapped by the JavaScript
1503-
External value
1506+
This API retrieves the external data pointer that was previously passed to
1507+
`napi_create_external()`.
15041508
15051509
#### *napi_get_value_int32*
15061510
<!-- YAML
@@ -2770,6 +2774,7 @@ napi_status napi_wrap(napi_env env,
27702774
Returns `napi_ok` if the API succeeded.
27712775
27722776
Wraps a native instance in JavaScript object of the corresponding type.
2777+
The native instance can be retrieved later using `napi_unwrap()`.
27732778
27742779
When JavaScript code invokes a constructor for a class that was defined using
27752780
`napi_define_class()`, the `napi_callback` for the constructor is invoked.
@@ -2788,11 +2793,15 @@ has a reference count of 0. Typically this reference count would be incremented
27882793
temporarily during async operations that require the instance to remain valid.
27892794
27902795
Caution: The optional returned reference (if obtained) should be deleted via
2791-
[`napi_delete_reference`][] ONLY in response to the finalize callback invocation.
2792-
(If it is deleted before then, then the finalize callback may never be
2793-
invoked.) Therefore when obtaining a reference a finalize callback is also
2796+
[`napi_delete_reference`][] ONLY in response to the finalize callback
2797+
invocation. (If it is deleted before then, then the finalize callback may never
2798+
be invoked.) Therefore when obtaining a reference a finalize callback is also
27942799
required in order to enable correct proper of the reference.
27952800
2801+
Note: This API may modify the prototype chain of the wrapper object.
2802+
Afterward, additional manipulation of the wrapper's prototype chain may cause
2803+
`napi_unwrap()` to fail.
2804+
27962805
### *napi_unwrap*
27972806
<!-- YAML
27982807
added: v8.0.0
@@ -2809,6 +2818,9 @@ napi_status napi_unwrap(napi_env env,
28092818

28102819
Returns `napi_ok` if the API succeeded.
28112820

2821+
Retrieves a native instance that was previously wrapped in a JavaScript
2822+
object using `napi_wrap()`.
2823+
28122824
When JavaScript code invokes a method or property accessor on the class, the
28132825
corresponding `napi_callback` is invoked. If the callback is for an instance
28142826
method or accessor, then the `this` argument to the callback is the wrapper

src/node_api.cc

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -819,9 +819,6 @@ napi_status napi_define_class(napi_env env,
819819
v8::Local<v8::FunctionTemplate> tpl = v8::FunctionTemplate::New(
820820
isolate, v8impl::FunctionCallbackWrapper::Invoke, cbdata);
821821

822-
// we need an internal field to stash the wrapped object
823-
tpl->InstanceTemplate()->SetInternalFieldCount(1);
824-
825822
v8::Local<v8::String> name_string;
826823
CHECK_NEW_FROM_UTF8(env, name_string, utf8name);
827824
tpl->SetClassName(name_string);
@@ -1950,14 +1947,24 @@ napi_status napi_wrap(napi_env env,
19501947
CHECK_ARG(env, js_object);
19511948

19521949
v8::Isolate* isolate = env->isolate;
1953-
v8::Local<v8::Object> obj =
1954-
v8impl::V8LocalValueFromJsValue(js_object).As<v8::Object>();
1950+
v8::Local<v8::Context> context = isolate->GetCurrentContext();
1951+
1952+
v8::Local<v8::Value> value = v8impl::V8LocalValueFromJsValue(js_object);
1953+
RETURN_STATUS_IF_FALSE(env, value->IsObject(), napi_invalid_arg);
1954+
v8::Local<v8::Object> obj = value.As<v8::Object>();
19551955

1956-
// Only objects that were created from a NAPI constructor's prototype
1957-
// via napi_define_class() can be (un)wrapped.
1958-
RETURN_STATUS_IF_FALSE(env, obj->InternalFieldCount() > 0, napi_invalid_arg);
1956+
// Create a wrapper object with an internal field to hold the wrapped pointer.
1957+
v8::Local<v8::ObjectTemplate> wrapperTemplate =
1958+
v8::ObjectTemplate::New(isolate);
1959+
wrapperTemplate->SetInternalFieldCount(1);
1960+
v8::Local<v8::Object> wrapper =
1961+
wrapperTemplate->NewInstance(context).ToLocalChecked();
1962+
wrapper->SetInternalField(0, v8::External::New(isolate, native_object));
19591963

1960-
obj->SetInternalField(0, v8::External::New(isolate, native_object));
1964+
// Insert the wrapper into the object's prototype chain.
1965+
v8::Local<v8::Value> proto = obj->GetPrototype();
1966+
wrapper->SetPrototype(proto);
1967+
obj->SetPrototype(wrapper);
19611968

19621969
if (result != nullptr) {
19631970
// The returned reference should be deleted via napi_delete_reference()
@@ -1988,11 +1995,15 @@ napi_status napi_unwrap(napi_env env, napi_value js_object, void** result) {
19881995
RETURN_STATUS_IF_FALSE(env, value->IsObject(), napi_invalid_arg);
19891996
v8::Local<v8::Object> obj = value.As<v8::Object>();
19901997

1991-
// Only objects that were created from a NAPI constructor's prototype
1992-
// via napi_define_class() can be (un)wrapped.
1993-
RETURN_STATUS_IF_FALSE(env, obj->InternalFieldCount() > 0, napi_invalid_arg);
1998+
// The object's prototype should be a wrapper with an internal field.
1999+
v8::Local<v8::Value> proto = obj->GetPrototype();
2000+
RETURN_STATUS_IF_FALSE(
2001+
env, !proto.IsEmpty() && proto->IsObject(), napi_invalid_arg);
2002+
v8::Local<v8::Object> wrapper = proto.As<v8::Object>();
2003+
RETURN_STATUS_IF_FALSE(
2004+
env, wrapper->InternalFieldCount() == 1, napi_invalid_arg);
19942005

1995-
v8::Local<v8::Value> unwrappedValue = obj->GetInternalField(0);
2006+
v8::Local<v8::Value> unwrappedValue = wrapper->GetInternalField(0);
19962007
RETURN_STATUS_IF_FALSE(env, unwrappedValue->IsExternal(), napi_invalid_arg);
19972008

19982009
*result = unwrappedValue.As<v8::External>()->Value();

test/addons-napi/test_object/test.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,3 +63,8 @@ assert(test_object.Has(object2, 'string'));
6363
assert(test_object.Has(object2, sym4));
6464
assert.strictEqual(test_object.Get(object2, 'string'), 'value');
6565
assert.strictEqual(test_object.Get(object2, sym4), 123);
66+
67+
// Wrap a pointer in a JS object, then verify that the pointer can be unwrapped.
68+
const wrapper = {};
69+
test_object.Wrap(wrapper);
70+
assert(test_object.Unwrap(wrapper));

test/addons-napi/test_object/test_object.c

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#include <node_api.h>
22
#include "../common.h"
33
#include <string.h>
4+
#include <stdlib.h>
45

56
napi_value Get(napi_env env, napi_callback_info info) {
67
size_t argc = 2;
@@ -138,13 +139,39 @@ napi_value Inflate(napi_env env, napi_callback_info info) {
138139
return obj;
139140
}
140141

142+
napi_value Wrap(napi_env env, napi_callback_info info) {
143+
size_t argc = 1;
144+
napi_value arg;
145+
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &arg, NULL, NULL));
146+
147+
int32_t* data = malloc(sizeof(int32_t));
148+
*data = 3;
149+
NAPI_CALL(env, napi_wrap(env, arg, data, NULL, NULL, NULL));
150+
return NULL;
151+
}
152+
153+
napi_value Unwrap(napi_env env, napi_callback_info info) {
154+
size_t argc = 1;
155+
napi_value arg;
156+
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &arg, NULL, NULL));
157+
158+
int32_t* data;
159+
NAPI_CALL(env, napi_unwrap(env, arg, &data));
160+
161+
napi_value result;
162+
NAPI_CALL(env, napi_get_boolean(env, data != NULL && *data == 3, &result));
163+
return result;
164+
}
165+
141166
void Init(napi_env env, napi_value exports, napi_value module, void* priv) {
142167
napi_property_descriptor descriptors[] = {
143168
DECLARE_NAPI_PROPERTY("Get", Get),
144169
DECLARE_NAPI_PROPERTY("Set", Set),
145170
DECLARE_NAPI_PROPERTY("Has", Has),
146171
DECLARE_NAPI_PROPERTY("New", New),
147172
DECLARE_NAPI_PROPERTY("Inflate", Inflate),
173+
DECLARE_NAPI_PROPERTY("Wrap", Wrap),
174+
DECLARE_NAPI_PROPERTY("Unwrap", Unwrap),
148175
};
149176

150177
NAPI_CALL_RETURN_VOID(env, napi_define_properties(

0 commit comments

Comments
 (0)