Skip to content

Commit be21678

Browse files
authored
src: keep reference buffer alive longer (#55)
* src: keep reference buffer alive longer Keep a buffer written by WritePointer alive until the finalizers for the buffer to which the pointer has been run have been executed: Refs: #54 Signed-off-by: Michael Dawson <[email protected]> * limit change to writePointer Update to avoid changing behaviour for _writePointer and limit change to writePointer where objects were already being associated with the buffer. Signed-off-by: Michael Dawson <[email protected]> * remove _attach call in writePointer remove _attach call in writePointer as it is no longer needed since a stronger version is done in the native code when true is passed as the fourth parameter
1 parent b0809c2 commit be21678

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

lib/ref.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -746,8 +746,12 @@ exports.writeObject = function writeObject (buf, offset, obj) {
746746

747747
exports.writePointer = function writePointer (buf, offset, ptr) {
748748
debug('writing pointer to buffer', buf, offset, ptr);
749-
exports._writePointer(buf, offset, ptr);
750-
exports._attach(buf, ptr);
749+
// Passing true as a fourth parameter does an a stronger
750+
// version of attach which ensures ptr is only collected after
751+
// the finalizer for buf has run. See
752+
// https://github.com/node-ffi-napi/ref-napi/issues/54
753+
// for why this is necessary
754+
exports._writePointer(buf, offset, ptr, true);
751755
};
752756

753757
/**

src/binding.cc

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -355,6 +355,18 @@ void WritePointer(const CallbackInfo& args) {
355355
if (input.IsNull()) {
356356
*reinterpret_cast<char**>(ptr) = nullptr;
357357
} else {
358+
if ((args.Length() == 4) && (args[3].As<Boolean>() == true)) {
359+
// create a node-api reference and finalizer to ensure that
360+
// the buffer whoes pointer is written can only be
361+
// collected after the finalizers for the buffer
362+
// to which the pointer was written have already run
363+
Reference<Value>* ref = new Reference<Value>;
364+
*ref = Persistent(args[2]);
365+
args[0].As<Object>().AddFinalizer([](Env env, Reference<Value>* ref) {
366+
delete ref;
367+
}, ref);
368+
}
369+
358370
char* input_ptr = GetBufferData(input);
359371
*reinterpret_cast<char**>(ptr) = input_ptr;
360372
}

0 commit comments

Comments
 (0)