quickjspp icon indicating copy to clipboard operation
quickjspp copied to clipboard

Write access into std::vector

Open i404788 opened this issue 4 years ago • 3 comments

Is it possible to set a member of std::vector in qjs? Currently only you can only write the full vector.

Test case:

template<typename _NumberT>
class Vector
{
public:
    std::vector<_NumberT> pos;
...
// Does not change value
for (let i = 0; i < vec.pos.length; i++)
    vec.pos[i] = 2;

// Works fine
vec.pos = [1,2,3,4];

i404788 avatar Feb 06 '20 16:02 i404788

I'm getting the same issue Is there a workaround for this?

MAG-mv avatar Jul 26 '22 15:07 MAG-mv

I 'resolved' this issue by implementing the extending the c++ class in javascript; I believe you can also implement a set(index, value) function to work around it and expose it, but not with actual js indexing afaik.

Example of extending pattern:

template <typename _NumberT>
class RobVector
{
public:
    std::vector<_NumberT> pos;
...
}
// Wrapper around RobVector
export class Vector extends _librob.RobVector {
    constructor(vec) {
        super(vec?.pos || (Array.isArray(vec) ? vec : undefined) || [])
        if (!isNaN(Number(vec))) {
            this.pos = Array(vec).fill(0);
        }
    }

    elementWise (b, op, defaultVal = 0) {
        // Requires full object copy (no member access)
        let ret = Array.from(this.pos);
        for (let i = 0; i < ret.length; i++) {
            ret[i] = op(ret[i], b.pos[i] || defaultVal, i)
        }
        return new Vector(ret);
    }

    toString()
    {
        let ret = Array.from(this.pos);
        return ret.join(", ")
    }
}

operators_set(Vector.prototype,{
        "-" (a, b) => a.elementWise(b, (x, y, i) => { return x - y; }, 0),
        "+" (a, b) => a.elementWise(b, (x, y, i) => { return x + y; }, 0)
});

i404788 avatar Jul 26 '22 15:07 i404788

Amazing, Thank-you

MAG-mv avatar Jul 26 '22 16:07 MAG-mv