leaningtech / cheerp-meta

Cheerp - a C/C++ compiler for Web applications - compiles to WebAssembly and JavaScript
https://labs.leaningtech.com/cheerp
Other
1.03k stars 51 forks source link

Conversion of std::vector<uint8_t> to UInt8Array #107

Closed niansa closed 3 years ago

niansa commented 3 years ago

Hey, I'm trying to convert a std::vector 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)?

niansa commented 3 years ago

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++

carlopi commented 3 years ago

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.