1.0.1 • Published 6 years ago

node-c-struct v1.0.1

Weekly downloads
2
License
ISC
Repository
github
Last release
6 years ago

Fundamental types

struct apic type
boolbool
charsigned char
ucharunsigned char
shortshort
ushortunsigned short
intint
uintunsigned int
longlong
ulongunsigned long
longlonglong long
ulonglongunsigned long long
floatfloat
doubledouble
ssize_tssize_t
size_tsize_t
int8_tint8_t
uint8_tuint8_t
int16_tint16_t
uint16_tuint16_t
int32_tint32_t
uint32_tuint32_t
int64_tint64_t
uint64_tuint64_t
structstruct
unionunion

Inheritance diagram

pic

built-in methods

  • get $buffer ()

    Return a node buffer

  • get $arrayBuffer ()

    Return an ArrayBuffer

  • get $address ()

    Return real address of current object

  • get $value ()

    Get value

  • set $value (value)

    Set value

Static methods

  • get byteSize ()

    Similar with sizeof()

  • times (length)

    Return an instance of BaseArrayType

Example

int

const struct = require('node-c-struct')

const a = new struct.int()

a.$value = 100

console.log(a) // <Buffer 64 00 00 00>
console.log(a.$value) // 100

array

const struct = require('node-c-struct')

const arr = new (struct.int.times(3))()

for (let i = 0; i < arr.length; i++) {
  arr[i].$value = i + 1
}

console.log(arr) // <Buffer 01 00 00 00 02 00 00 00 03 00 00 00>
console.log(arr[1].$value) // 2

union

const struct = require('node-c-struct')

class MyUnion extends struct.union {
  static get fields () {
    return [
      [ 'x', struct.char ],
      [ 'y', struct.int ]
    ]
  }
}

const a = new MyUnion()

a.$value = {
  'x': 266
}

console.log(a) // <Buffer 0a 00 00 00>
console.log(a.x.$value) // 10
console.log(a.y.$value) // 10

a.$value = {
  'y': 267
}

console.log(a) // <Buffer 0b 01 00 00>
console.log(a.x.$value) // 11
console.log(a.y.$value) // 267

struct

const struct = require('node-c-struct')

class Point extends struct.struct {
  static get fields () {
    return [
      [ 'x', struct.int ],
      [ 'y', struct.int ]
    ]
  }
}

const point = new Point({
  x: 1,
  y: 10
})

point.y.$value = 2

console.log(point) // <Buffer 01 00 00 00 02 00 00 00>

complex struct

const struct = require('node-c-struct')

class Point extends struct.struct {
  static get fields () {
    return [
      [ 'x', struct.int ],
      [ 'y', struct.int ]
    ]
  }
}

class MyStruct extends struct.struct {
  static get fields () {
    return [
      [ 'a', struct.char ],
      [ 's', Point ],
      [ 'b', struct.char.times(3) ]
    ]
  }
}

const s = new MyStruct()

s.a.$value = 1
s.s.x.$value = 2
s.s.y.$value = 3
s.b[0].$value = 4
s.b[1].$value = 5
s.b[2].$value = 6

console.log(s) // <Buffer 01 00 00 00 02 00 00 00 03 00 00 00 04 05 06 00>