1

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].

2
  • 2
    I can't test this, but let me know if this works: ref.get(myArray, someIndex, DataPointer).deref() or ref.get(ref.get(myArray, someIndex), 0, Data) Commented Feb 16, 2018 at 23:26
  • ref.get(myArray.buffer,0,DataPointer).deref() works. Thanks. I'll be happy to accept this as an answer. Commented Feb 18, 2018 at 18:04

1 Answer 1

1
+50

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.