File: handle_scope.md

package info (click to toggle)
node-addon-api 8.3.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,248 kB
  • sloc: cpp: 15,431; javascript: 5,631; ansic: 157; makefile: 7
file content (77 lines) | stat: -rw-r--r-- 2,242 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# HandleScope

The HandleScope class is used to manage the lifetime of object handles
which are created through the use of node-addon-api. These handles
keep an object alive in the heap in order to ensure that the objects
are not collected while native code is using them.
A handle may be created when any new node-addon-api Value or one
of its subclasses is created or returned. For more details refer to
the section titled [Object lifetime management](object_lifetime_management.md).

## Methods

### Constructor

Creates a new handle scope on the stack.

```cpp
Napi::HandleScope::HandleScope(Napi::Env env);
```

- `[in] env`: The environment in which to construct the `Napi::HandleScope` object.

Returns a new `Napi::HandleScope`

### Constructor

Creates a new handle scope on the stack.

```cpp
Napi::HandleScope::HandleScope(Napi::Env env, Napi::HandleScope scope);
```

- `[in] env`: `Napi::Env` in which the scope passed in was created.
- `[in] scope`: pre-existing `Napi::HandleScope`.

Returns a new `Napi::HandleScope` instance which wraps the `napi_handle_scope`
handle passed in.  This can be used to mix usage of the C Node-API
and node-addon-api.

```cpp
operator Napi::HandleScope::napi_handle_scope() const
```

Returns the Node-API `napi_handle_scope` wrapped by the `Napi::EscapableHandleScope` object.
This can be used to mix usage of the C Node-API and node-addon-api by allowing
the class to be used be converted to a `napi_handle_scope`.

### Destructor
```cpp
Napi::HandleScope::~HandleScope();
```

Deletes the `Napi::HandleScope` instance and allows any objects/handles created
in the scope to be collected by the garbage collector.  There is no
guarantee as to when the garbage collector will do this.

### Env

```cpp
Napi::Env Napi::HandleScope::Env() const;
```

Returns the `Napi::Env` associated with the `Napi::HandleScope`.

## Example

```cpp
for (int i = 0; i < LOOP_MAX; i++) {
  Napi::HandleScope scope(info.Env());
  std::string name = std::string("inner-scope") + std::to_string(i);
  Napi::Value newValue = Napi::String::New(info.Env(), name.c_str());
  // do something with newValue
};
```

For more details refer to the section titled [Object lifetime
management](object_lifetime_management.md).