通过函数调用为缓冲区分配内存
我有一个函数 f(q15_t *x, inst *z)
它有一个输入 x
和一个实例 z
:
typedef struct {
q15_t * pbuff;
}inst;
inst z;
我想要一个初始化函数能够分配内存空间并将其地址放置到 z.pbuff
中,就像(我的努力):
instance_initiator(inst *instance,uint16_t buffSize)
{
q15_t a[buffSize];
instance->pbuff=a;
}
我正在寻找正确的方法来执行此操作,因为我认为在启动器函数完成后,缓冲区分配的空间将消失了,看来我们需要全局变量和这不可能发生,可能是通过使 a
静态化?我希望能够做到这一点。
请注意,初始化将运行一次,该函数将被调用多次。
正如来自莫斯科的 Vlad 所说,malloc
很好,但我担心这是否会减慢算法?也许一种方法是通过宏设置静态数组a
的大小。
I have a function f(q15_t *x, inst *z)
it have an input x
and an instance z
:
typedef struct {
q15_t * pbuff;
}inst;
inst z;
I want an initializer function able to allocate memory space and place it's address to z.pbuff
, like (my effort):
instance_initiator(inst *instance,uint16_t buffSize)
{
q15_t a[buffSize];
instance->pbuff=a;
}
I'm searching for correct way to do this, since I think after initiator function finished the buffer allocated spaces will vanishes and it seems we need global variable and this can't happen may be by making a
static? I hope to being able to do this.
Note the initialization will run once and the function will be called many times.
As Vlad from Moscow told malloc
is good but I feel fear if that is slowing algorithm? Maybe one way is to set the size of static array a
by macro.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我找到了一个解决方案,但我不知道是否有人命名过这个解决方案:
这个解决方案是可能的,因为静态变量的大小假设在编译时已知,如果不是的话,缓冲区的大小决定仅在运行时,EZ 解决方案是使用 malloc,但(正如 Lundin 所说)嵌入式禁止动态分配,您可以使用 Lundin 的静态内存池解决方案。
I've found a solution but I don't know if ever anyone named this solution or not:
This solution has been possible since static variable's size assumed to be known in compile time, if that wasn't, and the size of buffer determines only in the run time, EZ solution is to use malloc but (as Lundin told) dynamic allocation is forbidden for embedded and you could use Lundin's static memory pool's solution.
使用
malloc()
进行分配。测试是否成功。不要害怕。查看过早优化真的是万恶之源吗?。
如果您仍然觉得
malloc()
很慢,请发布证明这一点的代码。Allocate using
malloc()
. Test for success.Have no fear. Review Is premature optimization really the root of all evil?.
If you still feel
malloc()
is slow, post code that demonstrates that.