TooTallNate / ref-struct

Create ABI-compliant "struct" instances on top of Buffers
119 stars 75 forks source link

Array of structs support? #11

Closed robgrimball closed 10 years ago

robgrimball commented 10 years ago

Nate,

I have a C function which accepts a pointer to the first structure in an array of structures, and a length to let it know how many such structures there are.

void * do_something(hosts * first_host, int num_hosts);

I am trying to use ref-struct (and ref-array at times) to try to build this in javascript to send off via ffi.

The problem is, I am getting a "RangeError: targetsStart out of bounds" error when I try to build the array. I imagine I am doing something wrong, but I can't figure out what as yet. I've tried building a ref-array via the following to test a simpler case and it fails with the above error :

    var HostInfo = ref_struct({test1: ref.types.int, test2: ref.types.int});
    var HostArray = ref_array(HostInfo, 2);

    var host0 = new HostInfo({test1: 1, test2: 3});
    var host1 = new HostInfo({test1: 2, test2: 4});

    var hosts = new HostArray();

    hosts[0] = host0;
    hosts[1] = host1;

Likewise I tried just packing these hosts into a buffer and get the same error :

    var buff = new Buffer(HostInfo.size * 2);
    HostInfo.set(buff, HostInfo.size * 0, host0);
    HostInfo.set(buff, HostInfo.size * 1, host1);

Any clue what I am doing wrong or how to go about this better? Your help/insight would be greatly appreciated.

Thanks,

Rob

TooTallNate commented 10 years ago

Thanks for pointing this out. You've actually uncovered a bug in ref-struct! I've fixed it in 9b20a3bdef806716bd2e58d7201d1cb31a3a3cea, and released v0.0.7 to fix it. Please update to this new version and let me know if you're still having troubles.

Additionally, I noticed a small typo in your code. You should define the HostArray type without a length field, and then when you create an instance of HostArray, then you specify the number of entries required in the Array and then an appropriately sized Buffer instance is created under the hood. Something like this:

var HostInfo = ref_struct({test1: ref.types.int, test2: ref.types.int});
var HostArray = ref_array(HostInfo);

var host0 = new HostInfo({test1: 1, test2: 3});
var host1 = new HostInfo({test1: 2, test2: 4});

var hosts = new HostArray(2);

hosts[0] = host0;
hosts[1] = host1;