Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a native finalizer example #48

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions HowtoFinalization.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,36 @@ mark-and-sweep finalizer
Cleaning up...
```

## Using a native finalizer

The finalizer function can also be a Duktape/C function. Here's an example
of setting up a finalizer from C code:

```c
/* Dummy object for finalization test. */
duk_push_object(ctx);

/* Finalizer gets a single argument, the object being finalized. */
duk_push_c_function(ctx, my_finalizer, 1 /*nargs*/);

/* Set finalizer. */
duk_set_finalizer(ctx, -2); /* [ object func ] -> [ object ] */

/* Object-with-finalizer left on stack top. */
```

The finalizer itself is an ordinary Duktape/C function:

```c
duk_ret_t my_finalizer(duk_context *ctx) {
/* Value stack index 0 has the object to be finalized. */
}
```

FIXME: add a concrete native resource, e.g. a FILE handle

FIXME: use an internal property, tolerate multiple finalization

## Adding a finalizer to a prototype object

If you have many objects of the same type, you can add a finalizer to the
Expand Down