簡體   English   中英

通過function調用分配memory緩沖

[英]Allocate memory to buffer through function call

我有一個 function f(q15_t *x, inst *z)它有一個輸入x和一個實例z

typedef struct {
q15_t * pbuff;
}inst;

inst z;

我想要一個初始化程序 function 能夠分配 memory 空間並將其地址放置到z.pbuff ,例如(我的努力):

instance_initiator(inst *instance,uint16_t buffSize)
{
q15_t a[buffSize];
instance->pbuff=a;
}

我正在尋找正確的方法來做到這一點,因為我認為在啟動器 function 完成后,緩沖區分配的空間將消失,看來我們需要全局變量,而這不可能發生可能是通過制作a 我希望能夠做到這一點。

請注意,初始化將運行一次,而 function 將被調用多次。

正如來自莫斯科的 Vlad 所說, malloc很好,但我擔心這是否會減慢算法? 也許一種方法是通過宏設置 static 數組a的大小。

我找到了一個解決方案,但我不知道是否有人將此解決方案命名為:

#define SIZEOFBUF 500

typedef struct {
q15_t * pbuff;
}inst;

typedef struct {
q15_t buff[SIZEOFBUF];
}instScratch;

inst_initiator(instScratch* scr,inst* z)
{
    inst->pbuff =instScratch->buff
}

void main(void)
{
    static instScratch scr;
    inst z;
    inst_initiator(&inst,&scr);

loop
{
f(x, &z);
}
}

這個解決方案是可能的,因為 static 變量的大小假定在編譯時已知,如果不是,並且緩沖區的大小僅在運行時確定,EZ 解決方案是使用 malloc 但是(正如 Lundin 所說)動態分配是禁止用於嵌入式,您可以使用 Lundin 的 static memory 池的解決方案。

使用malloc()進行分配。 測試成功。

// Return error flag
bool instance_initiator(inst *instance, uint16_t buffSize) {
  if (instance == NULL) {
    return true;
  }
  instance->pbuff = malloc(sizeof instance->pbuff[0] * buffSize);
  return instance->pbuff == NULL && buffSize == 0;
}

malloc 很好,但我擔心它是否會減慢算法?

沒有恐懼。 回顧過早的優化真的是萬惡之源嗎? .

如果您仍然覺得malloc()很慢,請發布演示代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM