Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

ref-napi

node-ffi-napi67.5kMIT3.0.3TypeScript support: definitely-typed

Turn Buffer instances into "pointers"

native, buffer, extensions, c++, pointer, reference, dereference, type, int, long, float, double, byte, 64, napi

readme

ref-napi

Turn Buffer instances into "pointers"

Greenkeeper badge

NPM Version NPM Downloads Build Status Coverage Status Dependency Status

This module is inspired by the old Pointer class from node-ffi, but with the intent of using Node's fast Buffer instances instead of a slow C++ Pointer class. These two concepts were previously very similar, but now this module brings over the functionality that Pointers had and Buffers are missing, so now Buffers are a lot more powerful.

Features:

  • Get the memory address of any Buffer instance
  • Read/write references to JavaScript Objects into Buffer instances
  • Read/write Buffer instances' memory addresses to other Buffer instances
  • Read/write int64_t and uint64_t data values (Numbers or Strings)
  • A "type" convention, so that you can specify a buffer as an int *, and reference/dereference at will.
  • Offers a buffer instance representing the NULL pointer

Installation

Install with npm:

$ npm install ref-napi

Examples

referencing and derefencing

var ref = require('ref-napi')

// so we can all agree that a buffer with the int value written
// to it could be represented as an "int *"
var buf = new Buffer(4)
buf.writeInt32LE(12345, 0)

// first, what is the memory address of the buffer?
console.log(buf.hexAddress())  // ← '7FA89D006FD8'

// using `ref`, you can set the "type", and gain magic abilities!
buf.type = ref.types.int

// now we can dereference to get the "meaningful" value
console.log(buf.deref())  // ← 12345


// you can also get references to the original buffer if you need it.
// this buffer could be thought of as an "int **"
var one = buf.ref()

// and you can dereference all the way back down to an int
console.log(one.deref().deref())  // ← 12345

See the full API Docs for more examples.

The "type" interface

You can easily define your own "type" objects at attach to Buffer instances. It just needs to be a regular JavaScript Object that contains the following properties:

Name Data Type Description
size Number The size in bytes required to hold this type.
indirection Number The current level of indirection of the buffer. Usually this would be 1_, and gets incremented on Buffers from ref() calls. A value of less than or equal to _0 is invalid.
get Function (buffer, offset) The function to invoke when dereferencing this type when the indirection level is 1.
set Function (buffer, offset, value) The function to invoke when setting a value to a buffer instance.
name String (optional) The name to use during debugging for this type.
alignment Number (optional) The alignment of this type when placed in a struct. Defaults to the type's size.

Be sure to check out the Wiki page of "Known Types", for the list of built-in ref types, as well as known external type implementations.

For example, you could define a "bigint" type that dereferences into a bigint instance:

var ref = require('ref-napi')
var bigint = require('bigint')

// define the "type" instance according to the spec
var BigintType = {
    size: ref.sizeof.int64
  , indirection: 1
  , get: function (buffer, offset) {
      // return a bigint instance from the buffer
      return bigint.fromBuffer(buffer)
    }
  , set: function (buffer, offset, value) {
      // 'value' would be a bigint instance
      var val = value.toString()
      return ref.writeInt64(buffer, offset || 0, val)
    }
}

// now we can create instances of the type from existing buffers.
// "buf" is some Buffer instance returned from some external data
// source, which should contain "bigint" binary data.
buf.type = BigintType

// and now you can create "bigint" instances using this generic "types" API
var val = buf.deref()
            .add('1234')
            .sqrt()
            .shiftLeft(5)

Build the docs

Install the dev dependencies:

$ npm install

Generate the docs:

$ npm run docs

Incompatible packages

The ref-struct-napi and ref-array-napi packages have names that sound like they are compatible with this module.

They are not, and your application will experience crashes if you use them together with ref-napi. Use ref-struct-di or ref-array-di instead.

License

(The MIT License)

Copyright (c) 2012 Nathan Rajlich <nathan@tootallnate.net> Copyright (c) 2017 Anna Henningsen <anna@addaleax.net> (N-API port)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

changelog

1.4.3 / 2020-01-16

  • [33d46e71db] - Update to jquery-3.4.1.min.js (Alan Ayoub) #23
  • [4b8f542c16] - chore: update marked to version 0.7.0 (greenkeeper[bot]) #17
  • [7137ebcfa1] - chore: update node-addon-api to version 2.0.0 (greenkeeper[bot]) #21

1.4.2 / 2019-01-07

  • [ed19a20370] - Fix readUInt64 so that it returns positive numbers when high order bit is set (Paul Elder) #20

1.4.1 / 2019-01-07

  • [f1827f3bdd] - Update node-addon-api dependency to ^1.6.2 (Anna Henningsen)
  • [bf16e880fb] - chore(package): update marked to version 0.6.0 (#11) (greenkeeper[bot])
  • [bb92877339] - Revert "Update debug to 4.0.0" (Anna Henningsen)
  • [6fa4022605] - Update debug to 4.0.0 (Anna Henningsen)
  • [3c98424bee] - chore(package): update marked to version 0.5.0 (#7) (greenkeeper[bot])
  • [c9523cd587] - chore(package): update nyc to version 12.0.1 (#6) (greenkeeper[bot])
  • [3f3f1b8efa] - chore(package): update marked to version 0.4.0 (#5) (greenkeeper[bot])
  • [1c2a878c7a] - chore(package): update mocha to version 5.0.0 (#2) (greenkeeper[bot])
  • [0b35b34000] - Explicitly test Node v4 (Anna Henningsen)
  • [74bbaa4cb6] - docs(readme): add Greenkeeper badge (greenkeeper[bot])
  • [bba04d75ce] - chore(package): update dependencies (greenkeeper[bot])
  • [0a77d1edde] - Bump node-addon-api to ^1.1.0 (Anna Henningsen)
  • [b8bac0aea0] - Use full package name in README heading (Anna Henningsen)
  • [31bd8454a7] - Use matching branch name for badges in README.md (Anna Henningsen)
  • [46b0db449b] - fix up package name in package.json (Anna Henningsen)

1.4.0 / 2017-11-19

  • [0cd2129acf] - Update information to new repository (Anna Henningsen)
  • [27171b2a96] - 🎉 Port code to N-API (Anna Henningsen)
  • [d23f403ab2] - Add missing LICENSE file to match package.json (Anna Henningsen)
  • [9523598530] - Add Code of Conduct (Anna Henningsen)
  • [f0790af04d] - Refactor tests to ES6 (Anna Henningsen)
  • [924437f94b] - fix readPointer() docs (#90) (John Cupitt)
  • [1029203b46] - don't fail in Node.js "6.0.0 && < 6.9.1" (#89) (btsimonh)
  • [4903350866] - Update docs about ref.address() being unsafe on 64-bit platforms (#88) (Yaacov Tarko)

1.3.5 / 2017-01-27

  • [a1b8216fe7] - fix util.inspect() overriding on Node v7 (Nathan Rajlich)
  • [0e26fcf81e] - appveyor: drop node v2 and v3 (Nathan Rajlich)
  • [9e9078a4e1] - travis: drop node v1 and v2 (Nathan Rajlich)
  • [615016ac1a] - test: fix util.inspect() test (Nathan Rajlich)
  • [e1fe604c05] - test: fix tests after V8 6.0 GC changes (Michaël Zasso, #85)

1.3.4 / 2017-01-27

  • [32637be7e4] - CI stuffs (Nathan Rajlich)
  • [55716fd9e3] - always use defineProperty() for name (Nathan Rajlich)
  • [786b73941e] - refType: force name to writable before updating it (Joel Martin) (#67)

1.3.3 / 2016-11-03

  • [3f0a2d4775] - rename History.md to CHANGELOG.md (Nathan Rajlich)
  • [30fe405ae5] - Merge pull request #62 from mhertsch/master (Nathan Rajlich)
  • [6fdb4b7b23] - Replaced ForceSet with Nan::ForceSet to remove deprecation warnings when using node 6.9.1 (Michael Hertsch)
  • [000b2a7889] - travis: test node v6 (Nathan Rajlich)

1.3.2 / 2016-01-10

  • int64: fix failing OS X tests now
  • int64: better error handling for Linux

1.3.1 / 2015-12-02

  • writeUInt64: better error checking for WriteUInt64()
  • writeUInt64: allow hex or octal input string values

1.3.0 / 2015-12-02

  • writeInt64: better error checking for WriteInt64()
  • writeInt64: allow hex or octal input string values
  • appveyor: test node v5
  • travis: test node v5

1.2.0 / 2015-10-08

  • force Buffer length to 0 if NULL is read (#42, @saneki)

1.1.3 / 2015-09-23

  • appveyor: remove v1
  • speed increase by avoiding JSON.stringify() constant call (#39, @dan-tull)

1.1.2 / 2015-09-19

1.1.1 / 2015-09-14

  • remove unused WrapPointer overload (fix compile warning)
  • appveyor: better Windows testing

1.1.0 / 2015-08-26

  • appveyor: 2.5 + 3 added
  • appveyor: attempt to fix v0.8 and v0.10
  • int64 conversion works with debug mode iojs runtime
  • persistent size fixed
  • better automated testing
  • package: update "weak" to v1
  • package: add "MIT" license field
  • NAN 2.0 support (#33, @unbornchikken)

1.0.2 / 2015-05-09

  • package: update "nan" to v1.8.4 (#30, @mafintosh)
  • README: use SVG for appveyor badge

1.0.1 / 2015-03-22

  • package: update "nan" to v1.7.0
  • appveyor: test node v0.12, don't test v0.11
  • travis: test node v0.12, don't test v0.11
  • README: add link to Known Types page

1.0.0 / 2015-01-20

  • bumping to v1.0.0 for better semver semantics
  • travis: don't test node v0.8.x

0.3.5 / 2015-01-18

  • src: add SET_SIZEOF and SET_ALIGNOF macros

0.3.4 / 2015-01-18

  • package: update "nan" to v1.5.1
  • travis: don't test node v0.6.x
  • use v8::Object::ForceSet instead of v8::Object:Set (#20, @sarangsapre)

0.3.3 / 2014-12-29

  • package: allow any "debug" v2
  • add support for Buffer#reinterpret() with offset (#18, @deepak1556)

0.3.2 / 2014-06-19

  • src: fix comment typo
  • src: define our own kMaxLength constant

0.3.1 / 2014-06-09

  • src: allow Buffers returned from reinterpretUntilZeros() up to kMaxLength bytes
  • test: move the reinterpretUntilZeros() tests to their own file
  • test: fix Buffer#inspect() test on Windows

0.3.0 / 2014-06-08

  • ref: use hexAddress() for the Buffer inspect() override
  • ref: add hexAddress() function
  • src: use NanEscapableScope where appropriate
  • src: use uintptr_t to ensure a positive address
  • src: better snprintfs #define macro (#12, @fjhub)
  • package: update "debug" to v1.0.1

0.2.3 / 2014-06-04

  • package: update "nan" to v1.2.0
  • src: remove commented code

0.2.2 / 2014-06-01

  • package: update "nan" to v1.1.2
  • travis: remove IRC notifications from Travis

0.2.1 / 2014-05-27

  • package: pin dev dependency versions
  • package: use explicit nan commit with LLVM fix
  • README: use https for Travis URL
  • travis: test node v0.6.x

0.2.0 / 2014-05-26

  • binding: use rvagg/nan for node v0.8, v0.10, and v0.11 compat
  • package: update "nan" to v1.1.0
  • package: remove "engines" section
  • README: add appveyor test badge
  • README: use .svg for Travis badge
  • add appveyor.yml file
  • .travis: don't test node v0.9.x
  • package: beautify
  • add a persistent option to writeObject()
  • make passing ref.NULL to allocCString() work as expected
  • docs: document the "length" parameter of ref.readPointer()

0.1.3 / 2012-09-25

  • fix compiler warnings on Windows

0.1.2 / 2012-09-02

  • allow an offset as the third argument to the "reinterpret" functions

0.1.1 / 2012-08-03

  • prevent multiple instances of ref from chaining inspects in "overwriteInspect"

0.1.0 / 2012-07-22

  • initial release of the documentation (http://tootallnate.github.com/ref)
  • binding: make "endianness" and "NULL" be 'frozen'
  • lib: make derefType() throw an Error when given a "type" with indirection 1
  • augment the Buffer#inspect() function to print out the memory address as well

0.0.20 / 2012-06-27

  • rename the Utf8String type to CString (#5)
  • make Utf8String an alias to CString and deprecated
  • more work on docs (not yet ready)

0.0.19 / 2012-06-25

  • use node-bindings

0.0.18 / 2012-06-21

  • add the non-native-endian read+write int64 functions
  • starting on some real (inline) documentation

0.0.17 / 2012-06-05

  • allow the "bool" type to write arbitrary number values (0-255) to it
  • Utf8String: return JS null when reading a pointer pointing to NULL
  • make reinterpret() and reinterpretUntilZeros() throw an Error when given a NULL pointer
  • make ref.get() and ref.set() coerce their optional type when given
  • some more tests

0.0.16 / 2012-06-01

  • use Object.create() and Object.getPrototypeOf() for refType() and derefType()
  • remove cloneType()
  • make reading from a NULL pointer always throw an Error:
    • readCString()
    • readPointer()
    • readObject()
    • readInt64()
    • readUInt64()

0.0.15 / 2012-05-31

  • fix possible segmentation fault with readObject()
  • fix possible segmentation fault with readPointer()

0.0.14 / 2012-05-31

  • fix possible segmentation fault with readCString()

0.0.13 / 2012-05-30

  • make refType() coerce string types properly
  • make the bool type inherit from a proper fixed type (like uint8)

0.0.12 / 2012-05-30

  • make the "char" and "uchar" types accept JS String values
  • make the synonym types (i.e. longlong is a synonym for int64) be distinct objects, rather than simple JS references
  • fix coersion of a string value of "Object"
  • added the reinterpretUntilZeros() function

0.0.11 / 2012-05-17

  • always do string type coersion, like on alloc()
  • add a "bool" type, which works with JS true/false values

0.0.10 / 2012-05-15

  • fix compiler error on Solaris
  • fix compiler errors on Windows

0.0.9 / 2012-05-13

  • allow ref.alloc() to not have a value being set with it
  • add the coerceType() function (get a proper "type" instance from a string)
  • add the Utf8String type back over from node-ffi
  • conditionally extend SlowBuffer.prototype for node >= v0.7.9

0.0.8 / 2012-05-12

  • make the void type "set()" function be a no-op instead of throwing
  • added some more test cases

0.0.7 / 2012-05-09

  • added the reinterpret() function

0.0.6 / 2012-05-09

  • add alignof mappings for the types
  • add an Object type
  • set the alignment property on the built-in types

0.0.5 / 2012-05-09

  • quickly add get() and set() functions
  • use the PRId64 and PRIu64 snprintf types

0.0.4 / 2012-05-08

  • README improvements; some API documentation
  • removed some leftover debugging statements

0.0.3 / 2012-05-08

  • added readCString() function (to Buffer.prototype as well)
  • added writeCString() function (to Buffer.prototype as well)
  • added an allocCString() function
  • removed the Utf8String type; moved it to node-ffi
  • made ref.NULL be a 'void' type

0.0.2 / 2012-05-05

  • Added missing includes for Linux, etc.

0.0.1 / 2012-05-04

  • Initial release