【问题标题】:How to pass an array into a function without using vectors in emscription?如何在不使用向量的情况下将数组传递给函数?
【发布时间】:2021-09-25 01:25:53
【问题描述】:

我基本上到处都看过,我找不到任何关于这个问题的文档。我想在 em++ 中将 JS 数组作为 C 数组传递,而我发现的所有内容都使用向量。使用向量,您必须将每个值一个一个推回,然后将其传递给 C++ 函数。这很慢而且很不方便,所以我想知道一个正常的 C 数组方式来做这件事。
对于上下文,我想做这样的事情:

int
add(const int test[], const int size)
{
    int res = 0;
    for (int i = 0; i < size; i++)
        res += test[i];
    return res;
};

【问题讨论】:

  • 你不能用const auto data = emscripten::convertJSArrayToNumberVector&lt;float&gt;(input);
  • 这也可能是你要找的medium.com/@tdeniffel/…

标签: javascript c++ webassembly emscripten


【解决方案1】:

你可以用这个语法来做(使用 int** 会丢失大小信息,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);

}

【讨论】:

    猜你喜欢
    • 2014-09-29
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    • 2019-07-13
    • 2013-11-10
    相关资源
    最近更新 更多