0

I've looked basically everywhere, and I can't find any documentation about this question. I want to pass a JS array as a C-array in em++, and everything I've found uses vectors. With vectors, you have to push back every value one by one then pass it into the C++ function. This is slow and really inconvenient, so I'd like to know of a normal C-array way of doing this.
For context, I want to do something like this:

int
add(const int test[], const int size)
{
    int res = 0;
    for (int i = 0; i < size; i++)
        res += test[i];
    return res;
};
Ari
  • 31
  • 4
  • Could you not use `const auto data = emscripten::convertJSArrayToNumberVector(input);` – Juicestus Sep 25 '21 at 01:49
  • Also this might be what you're looking for https://medium.com/@tdeniffel/c-to-webassembly-pass-and-arrays-to-c-86e0cb0464f5 – Juicestus Sep 25 '21 at 01:50

1 Answers1

0

You can do it with this syntax (using int** will lose size information, What is array to pointer decay?):

#include <utility>

// For an array of size 4
int add4(const int(&values)[4])
{
    int sum{ 0 };

    // if you cant use range based fors
    for (std::size_t n = 0; n < 4; ++n) sum += values[n];
    return sum;
}

// For any const sized array
// with this syntax you don't lose size information on the array
template<std::size_t N>
int add(const int(&values)[N])
{
    int sum{ 0 };

    // I prefer range based fors
    for (const int value : values) sum += value;
    return sum;
}


int main()
{
    int values[4] { 1,2,3,4 };
    int sum4 = add4(values);

    // compiler will know array has size 8
    int values8[]{ 1,2,3,4,5,6,7,8 }; 
    int sum8 = add(values8);

}
Pepijn Kramer
  • 9,356
  • 2
  • 8
  • 19