Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Write access into std::vector #10

Open
i404788 opened this issue Feb 6, 2020 · 3 comments
Open

Write access into std::vector #10

i404788 opened this issue Feb 6, 2020 · 3 comments

Comments

@i404788
Copy link
Contributor

i404788 commented Feb 6, 2020

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];
@MAG-mv
Copy link

MAG-mv commented Jul 26, 2022

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

@i404788
Copy link
Contributor Author

i404788 commented Jul 26, 2022

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)
});

@MAG-mv
Copy link

MAG-mv commented Jul 26, 2022

Amazing, Thank-you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants