title: Converting node.js buffer into a ref-struct instance
body: <p>I am writing a program in both C and Javascript (on node.js), using <a href="https://www.npmjs.com/package/ffi" rel="nofollow noreferrer">ffi</a>, <a href="https://www.npmjs.com/package/ref" rel="nofollow noreferrer">ref</a>, and a few other ref- packages.</p>
  
  <p>I have the following code, which I compile into a library libfun.so:</p>
  
  <p>fun.c</p>
  
  <pre><code>#include "fun.h"
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  
  void fill_array(void **data_array, int length)
  {
      int i;
      for (i = 0; i &lt; length; i++) {
          data_array[i] = malloc(sizeof(data));
          ((data *)data_array[i])-&gt;id = 256;
          ((data *)data_array[i])-&gt;message = 512;
      }   
  }
  
  void print_array(void **data_array, int length)
  {
      int i = 0;
      for (i = 0; i &lt; length; i++) {
          printf("(%d, %d)\n", ((data *)data_array[i])-&gt;id, 
                 ((data *)data_array[i])-&gt;message);
      }
  }
  </code></pre>
  
  <p>fun.h</p>
  
  <pre><code>#ifndef fun_h__
  #define fun_h__
  
  typedef struct {
      int id;
      int message;
  } data;
  
  void fill_array(void **,int);
  void print_array(void **,int);
  
  #endif
  </code></pre>
  
  <p>fun.js</p>
  
  <pre><code>var ffi = require('ffi');
  var Struct = require('ref-struct');
  var ref = require('ref');
  var ArrayType = require('ref-array');
  
  // js analog of the data struct from fun.h
  var Data = Struct({
    id: ref.types.int,
    message: ref.types.int,
  });
  // js analog of the type data *
  var DataPointer = ref.refType(Data);
  
  // pvoid is the js analog of void * in C
  var pvoid = ref.refType(ref.types.void);
  var PVoidArray = ArrayType(pvoid);
  
  // set up our foreign functions from libfun
  var libfun = ffi.Library('./libfun', {
      'fill_array' : ['void', [PVoidArray,ref.types.int]],
      'print_array' : ['void', [PVoidArray, ref.types.int]]
  });
  var myArray = new PVoidArray(10);
  libfun.fill_array(myArray,10);
  libfun.print_array(myArray,10); // this prints the array of structs correctly, from the C side
  </code></pre>
  
  <p>My question is: how can I print the array of structs <strong>from the Javascript side</strong>? <strong>I want to pass myArray in as a <code>PVoidArray</code>.</strong> I do not want to create an array of structs (i.e. create <code>var DataArray = ArrayType(DataPointer)</code>, and use that instead of <code>PVoidArray</code> everywhere). </p>
  
  <p>Let's start with myArray[0]. Can we use our variable <code>Data</code> to (in a flexible way) take <code>myArray[0]</code> and make a struct? Like some function <code>bufferToArray(myArray[0],Data) == a Data instance containing the data of myArray[0]</code>. </p>