leaningtech/cheerp-meta

Conversion of std::vector<uint8_t> to UInt8Array

niansa opened this issue · 2 comments

Hey, I'm trying to convert a std::vector<uint8_t> to client::UInt8Array, however there is no way to read data into the object.

This is my current code:

inline client::Uint8Array *toJsU8Arr(const std::vector<uint8_t>& data) {
    auto array = new client::Uint8Array(data.size());
    auto source = data.begin();
    array->forEach(cheerp::Callback([&] (client::Number *item) {
        *item = *(source++);
    }));
    return array;
}

However it results in a null-array. Is there a better way to do do that (and vice-versa)?

I figured out the way C++ -> JS:

inline client::Uint8Array *toJsU8Arr(const std::vector<uint8_t>& data) {
    auto array = new client::Uint8Array(data.size());
    for (auto it = 0; it != data.size(); it++) {
        (*array)[it] = data[it];
    }
    return array;
}

But still can't figure out JS -> C++

Your solution should be adaptable also in the other direction:

inline std::vector<uint8_t> toCppVector(client::Uint8Array* array) {
    std::vector<uint8_t> data(array->get_length());
    for (auto it = 0; it != data.size(); it++) {
        data[it] = (*array)[it];
    }   
    return data;
}

Does this solve your problem? I will close the issue for now.