使用Node.js ffi模块分配无符号字符的缓冲区

时间:2014-03-18 23:42:04

标签: c arrays node.js node-ffi

我使用ffi和ref模块为Node.js创建绑定到codec2 C library

这是library's header

的一部分
#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[]);

以下是C(c2enc.c)中编码的示例实现:

#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);
    }
    /* ... */
}

这就是我尝试从JavaScript代码调用encode函数的方式:

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);

您能否解释一下如何正确分配unsigned char* bits数组和short数组?因为我怀疑我是否正确地做到了。在参考库文档中,我发现可以分配字符串,但没有参考如何创建其他一些数据类型的数组。

顺便说一下,如果重要的话我会使用节点0.10.26。

1 个答案:

答案 0 :(得分:0)

事实证明,这很简单。我刚刚使用了节点本机缓冲区。

var buf = new Buffer(short.size * CODEC2_SAMPLES_PER_FRAME)
var bits = new Buffer(uchar.size * BITS_SIZE)

for (var i=0; i < uchar.size*BITS_SIZE; i++) {
  uchar.set(bits, uchar.size*i, 0)
}

Codec2.codec2_encode(codec2, bits, buf);

它有效!