Search code examples
javascriptc++node.jsmemorytyped-arrays

Pointer to a subarray of TypedArray


Imagine we have

var a = new Float64Array([1, 2, 3]),
    b = new Float64Array([4, 5]);

var c = new Float64Array(a.length + b.length);

Now I want to combine a and b into c. I have written a C++ BLAS binding to copy data between two double/single precision arrays. Thing is, this binding has no offset attribute:

void cblas_dcopy(int n, const double *x, const int inc_x, const double *y, const int inc_y);

Can I get a subarray pointing to an offset of c's memory space? The following is called in JavaScript:

// copy first to result, works
cblas_dcopy(3, a, 1, c, 1);

// does not work because slice() returns a copy
cblas_dcopy(2, b, 1, c.slice(a.length), 1);

// now how would I copy to c at offset b.length?

Solution

  • You can actually do this easily without a C++ binding:

    var a = new Float64Array([1, 2, 3]);
    var b = new Float64Array([4, 5]);
    var c = new Float64Array(a.length + b.length);
    c.set(a, 0);
    c.set(b, a.length);
    

    To get the subarray as you asked, try using typedarray.subarray([begin[, end]]).