title: Allocate buffer of unsigned chars using Node.js ffi module
body: <p>I'm using ffi and ref modules for Node.js to create bindings to <a href="https://github.com/DanielO/codec2" rel="nofollow">codec2 C library</a>.</p>
  
  <p>This is the part of the <a href="https://github.com/DanielO/codec2/blob/master/src/codec2.h" rel="nofollow">library's header</a>:</p>
  
  <pre class="lang-c prettyprint-override"><code>#define CODEC2_SAMPLES_PER_FRAME 160
  #define CODEC2_BITS_PER_FRAME     50
  void *codec2_create();
  void codec2_encode(void *codec2_state, unsigned char * bits, short speech_in[]);
  </code></pre>
  
  <p>Here is the example implementation of encoding in C (<a href="https://github.com/DanielO/codec2/blob/master/src/c2enc.c" rel="nofollow">c2enc.c</a>):</p>
  
  <pre class="lang-c prettyprint-override"><code>#define BITS_SIZE   ((CODEC2_BITS_PER_FRAME + 7) / 8)
  int main(int argc, char *argv[])
  {
      void *codec2;
      FILE *fin;
      FILE *fout;
      short buf[CODEC2_SAMPLES_PER_FRAME];
      unsigned char  bits[BITS_SIZE];
      /* ... */
      codec2 = codec2_create();
  
      while(fread(buf, sizeof(short), CODEC2_SAMPLES_PER_FRAME, fin) ==
        CODEC2_SAMPLES_PER_FRAME) {
      codec2_encode(codec2, bits, buf);
      fwrite(bits, sizeof(char), BITS_SIZE, fout);
      //if this is in a pipeline, we probably don't want the usual
          //buffering to occur
          if (fout == stdout) fflush(stdout);
          if (fin == stdin) fflush(stdin);
      }
      /* ... */
  }
  </code></pre>
  
  <p>And that's how I'm trying to call <code>encode</code> function from JavaScript code:</p>
  
  <pre class="lang-js prettyprint-override"><code>CODEC2_SAMPLES_PER_FRAME  = 160
  CODEC2_BITS_PER_FRAME     = 50
  BITS_SIZE   = ((CODEC2_BITS_PER_FRAME + 7) / 8)
  
  var Codec2 = ffi.Library('./libcodec2', {
  
  
  "codec2_create": [ 'pointer', [] ],
    "codec2_destroy": [ "void", [ref.refType('void')] ],
    "codec2_encode": [ "void", [
        ref.refType('void'), 
        ref.refType('uchar') , 
        ref.refType('short') 
        ] 
    ],
    "codec2_decode": [ "void", [
        ref.refType('void'), 
        ref.refType('short'),
        ref.refType('uchar') 
        ] 
    ]
  });
  
  var codec2 = Codec2.codec2_create();
  
  var buf = ref.alloc('short', CODEC2_SAMPLES_PER_FRAME)
  var bits = ref.alloc('uchar', BITS_SIZE)
  Codec2.codec2_encode(codec2, bits, buf);
  
  Codec2.codec2_destroy(codec2);
  </code></pre>
  
  <p>Could you please explain how to properly allocate array of <code>unsigned char* bits</code> and array of <code>short</code>? Because I doubt I'm doing it properly. In ref library docs I've found that it's possible to allocate string, but no reference on how to create an array of some other data types.</p>
  
  <p>BTW, I'm using node 0.10.26 if that matters.</p>