如何在不使用向量的情况下将数组传递给函数?

Posted

技术标签:

【中文标题】如何在不使用向量的情况下将数组传递给函数?【英文标题】: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/… 【参考方案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);


【讨论】:

以上是关于如何在不使用向量的情况下将数组传递给函数?的主要内容,如果未能解决你的问题,请参考以下文章

如何在不循环的情况下将数组的内容复制到 C++ 中的 std::vector?

如何在不使用角度的ng的情况下将输入值从父组件传递给子组件?

如何在不复制的情况下将画布 imageData 传递给 emscripten c++ 程序?

如何在不为其分配内存的情况下将缓冲区传递给 write()

如何在不覆盖 TTY 的情况下将密码传递给 su/sudo/ssh?

如何在不将图像保存在本地的情况下将捕获的图像(Surface View)传递给另一个片段?