函数 return 是 Vivado HLS 中可能的数组吗?
Is function return an array possible in Vivado HLS?
这样的函数:
int * getRandom( ) {
static int r[10];
int i;
/* set the seed */
srand( (unsigned)time( NULL ) );
for ( i = 0; i < 10; ++i) {
r[i] = rand();
printf( "r[%d] = %d\n", i, r[i]);
}
return r;
}
这个可以用在Vivado HLS中吗?如果可能的话,我怎么能初始化一个未知大小的数组,因为我不能再使用 static
和 malloc
?
正在将评论转化为答案。
在标准 C 中,您不能 return 来自函数的数组 — 您可以 return 指针 OK(因此显示的代码是允许的,尽管它显然具有可重入性和线程问题)。如果您不能使用 static
或 malloc()
等,那么您需要将数组传递给函数以供其填充,而不是 returning 数组。那么调用者有责任分配 space.
另见 srand() — why call it only once。
So you mean I can set a global array as function arguments and give value to each element so I can get the array without using static
and malloc
?
是的,或者本地数组,或者您想要的任何其他类型的数组。我认为适当的实施可能是:
void getRandom(int n_vals, int *i_vals)
{
for (int i = 0; i < n_vals; i++)
i_vals[i] = rand();
}
但可能的变体很多。如果您确实需要,可以恢复打印;如果你真的想,你甚至可以调用 srand()
(但你应该只调用一次)。然后你可以像这样使用它:
void somefunc(void)
{
int data[20];
getRandom(15, data);
…use data…;
}
或
static int data[20];
void somefunc(void)
{
getRandom(18, data);
…use data…;
}
或其他变体(例如不在 data
的文件范围定义前使用 static
— 将其转换为全局变量)。 (是的,您可能会在问题中使用 10,或者在数组中使用 20 作为 space 的数量——但是 15 和 18 在它们的上下文中也是可以的值。)
这样的函数:
int * getRandom( ) {
static int r[10];
int i;
/* set the seed */
srand( (unsigned)time( NULL ) );
for ( i = 0; i < 10; ++i) {
r[i] = rand();
printf( "r[%d] = %d\n", i, r[i]);
}
return r;
}
这个可以用在Vivado HLS中吗?如果可能的话,我怎么能初始化一个未知大小的数组,因为我不能再使用 static
和 malloc
?
正在将评论转化为答案。
在标准 C 中,您不能 return 来自函数的数组 — 您可以 return 指针 OK(因此显示的代码是允许的,尽管它显然具有可重入性和线程问题)。如果您不能使用 static
或 malloc()
等,那么您需要将数组传递给函数以供其填充,而不是 returning 数组。那么调用者有责任分配 space.
另见 srand() — why call it only once。
So you mean I can set a global array as function arguments and give value to each element so I can get the array without using
static
andmalloc
?
是的,或者本地数组,或者您想要的任何其他类型的数组。我认为适当的实施可能是:
void getRandom(int n_vals, int *i_vals)
{
for (int i = 0; i < n_vals; i++)
i_vals[i] = rand();
}
但可能的变体很多。如果您确实需要,可以恢复打印;如果你真的想,你甚至可以调用 srand()
(但你应该只调用一次)。然后你可以像这样使用它:
void somefunc(void)
{
int data[20];
getRandom(15, data);
…use data…;
}
或
static int data[20];
void somefunc(void)
{
getRandom(18, data);
…use data…;
}
或其他变体(例如不在 data
的文件范围定义前使用 static
— 将其转换为全局变量)。 (是的,您可能会在问题中使用 10,或者在数组中使用 20 作为 space 的数量——但是 15 和 18 在它们的上下文中也是可以的值。)