I am writing a program in both C and Javascript (on node.js), using ffi, ref, and a few other ref- packages.
I have the following code, which I compile into a library 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
My question is: how can I print the array of structs from the Javascript side? I want to pass myArray in as a PVoidArray
. I do not want to create an array of structs (i.e. create var DataArray = ArrayType(DataPointer)
, and use that instead of PVoidArray
everywhere).
Let's start with myArray[0]. Can we use our variable Data
to (in a flexible way) take myArray[0]
and make a struct? Like some function bufferToArray(myArray[0],Data) == a Data instance containing the data of myArray[0]
.
Looking at the documentation for ref.get()
, you could use that:
ref.get(myArray.buffer, index, DataPointer).deref()
will return an instance of Data
from index
of myArray
.