我正在使用ffi,ref和其他一些参考包在C和Javascript(在node.js上)编写程序。
我有以下代码,我编译成库libfun.so:
fun.c
#include "fun.h"
#include <stdio.h>
#include <stdlib.h>
void fill_array(void **data_array, int length)
{
int i;
for (i = 0; i < length; i++) {
data_array[i] = malloc(sizeof(data));
((data *)data_array[i])->id = 256;
((data *)data_array[i])->message = 512;
}
}
void print_array(void **data_array, int length)
{
int i = 0;
for (i = 0; i < length; i++) {
printf("(%d, %d)\n", ((data *)data_array[i])->id,
((data *)data_array[i])->message);
}
}
fun.h
#ifndef fun_h__
#define fun_h__
typedef struct {
int id;
int message;
} data;
void fill_array(void **,int);
void print_array(void **,int);
#endif
fun.js
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
我的问题是:如何从Javascript端打印结构数组 ? 我想将myArray作为PVoidArray
传递。我不想创建一个结构数组(即创建var DataArray = ArrayType(DataPointer)
,并使用它而不是PVoidArray
到处)。
让我们从myArray [0]开始。我们可以使用变量Data
(以灵活的方式)获取myArray[0]
并制作结构吗?像一些函数bufferToArray(myArray[0],Data) == a Data instance containing the data of myArray[0]
。
答案 0 :(得分:1)