Create ABI-compliant "struct" instances on top of Buffers. Supports Node 6, 7, 8, 10, 12.
npm install ref-struct-napiref-struct-napi
==========
npm:
bash
$ npm install ref-struct-napi
`
Examples
--------
Say you wanted to emulate the timeval struct from the stdlib:
` c
struct timeval {
time_t tv_sec; / seconds since Jan. 1, 1970 /
suseconds_t tv_usec; / and microseconds /
};
`
` js
var ref = require('ref-napi')
var StructType = require('ref-struct-napi')
// define the time types
var time_t = ref.types.long
var suseconds_t = ref.types.long
// define the "timeval" struct type
var timeval = StructType({
tv_sec: time_t,
tv_usec: suseconds_t
})
// now we can create instances of it
var tv = new timeval
`
#### With node-ffi
This gets very powerful when combined with node-ffi to invoke C functions:
` js
var ffi = require('ffi')
var tv = new timeval
gettimeofday(tv.ref(), null)
`
#### Progressive API
You can build up a Struct "type" incrementally (useful when interacting with a
parser) using the defineProperty() function. But as soon as you _create_ an
instance of the struct type, then the struct type is finalized, and no more
properties may be added to it.
` js
var ref = require('ref-napi')
var StructType = require('ref-struct-napi')
var MyStruct = StructType()
MyStruct.defineProperty('width', ref.types.int)
MyStruct.defineProperty('height', ref.types.int)
var i = new MyStruct({ width: 5, height: 10 })
MyStruct.defineProperty('weight', ref.types.int)
// AssertionError: an instance of this Struct type has already been created, cannot add new "fields" anymore
// at Function.defineProperty (/Users/nrajlich/ref-struct/lib/struct.js:180:3)
``