TooTallNate / ref-struct

Create ABI-compliant "struct" instances on top of Buffers
118 stars 78 forks source link

[Need Help] How to access a structure array, returned from C as pointer? #39

Open engrvivs-neosoft opened 4 years ago

engrvivs-neosoft commented 4 years ago

Hi

Through list_buckets() C function, I am retrieving a C structure, BucketList, through ref-struct, defined as follows:

const BucketList = struct({
    more  : ref.types.bool,
    items : ref.refType(BucketInfo),
    length: "int32"
});

Here, I mainly need to access the "array" of BucketInfo, which I have declared as follows:

const BucketInfo = struct({
    name                 : ref.refType(ref.types.CString),
    created              : "int64",
    path_cipher          : "uint32",
    segment_size         : "uint64",
    encryption_parameters: EncryptionParameters,
    redundancy_scheme    : RedundancyScheme
});

const EncryptionParameters = struct({
    cipher_suite: "uint32",
    block_size  : "int32"
});

const RedundancyScheme = struct({
    algorithm      : "uint32",
    share_size     : "int32",
    required_shares: "int16",
    repair_shares  : "int16",
    optimal_shares : "int16",
    total_shares   : "int16"
});

Although, I am able to access the first bucket's information, through BucketList.items. But, I am not able to "point" to the next bucket's information.

May someone hint, as to how I may access the next information?

Thank in Advance Vivs

pierre-arlaud commented 3 years ago

@engrvivs-neosoft have you managed to do this in the end? I tried using readPointer and get with an offset to get the next element but this results in "Buffer instance must be at least 32 bytes to back this struct type"

pierre-arlaud commented 3 years ago

Oh I have finally found it. It was difficult because the full api doc of ref is missing but for anyone who falls onto this:

The buffer is allocated for only one structure by default (as it is a pointer) so you need to use the reinterpret function:

    // const structType = new StructType({…});
    const myStructType = ref.refType(structType);
    const result = myLibraryStruct.reinterpret(n * myStructType.size); // with n being the number of elements in the array
    let el = ref.get(result, i * myStructType.size, structType); // retrieves the element in the array at rank i