使用ZLIB deflateBound()动态地

问题描述 投票:0回答:1

我一直在寻找如何动态地使用deflateBound(),并没有发现正是我所期待的。

我看了看手册ZLIP,包括在库的例子,发现这些在这里:Compression Libraries for ARM Cortex M3/4 Determine compressed/uncompressed buffer size for Z-lib in C zlib, deflate: How much memory to allocate?

我所缺少的是如何调用deflateBound后分配()。例如。这看起来像它会引起问题

   z_stream defstream;
   uint8_t *outBuf=NULL;
   uint32_t outLen=0;

   defstream.zalloc = Z_NULL;
   defstream.zfree = Z_NULL;
   defstream.opaque = Z_NULL;
   defstream.avail_in = (uInt)inLen;
   defstream.next_in = (Bytef *)inBuf:
   defstream.avail_out = (uInt)0;
   defstream.next_out = (Bytef *)outBuf;

   deflateInit(&defstream, Z_DEFAULT_COMPRESSION);
   uint32_t  estimateLen = deflateBound(&defstream, inLen);
   outBuf = malloc(estimateLen);
   defstream.avail_out = (uInt)estimateLen;
   deflate(&defstream, Z_FINISH);
   deflateEnd(&defstream);

我看到的realloc被提及,这是否意味着,最初(可能太小)缓冲开始建议?

   z_stream defstream;
   uint8_t *outBuf=NULL;
   uint32_t outLen=100;
   outBuf = malloc(outLen);

   defstream.zalloc = Z_NULL;
   defstream.zfree = Z_NULL;
   defstream.opaque = Z_NULL;
   defstream.avail_in = (uInt)inLen;
   defstream.next_in = (Bytef *)inBuf:
   defstream.avail_out = (uInt)outLen;
   defstream.next_out = (Bytef *)outBuf;

   deflateInit(&defstream, Z_DEFAULT_COMPRESSION);
   uint32_t  estimateLen = deflateBound(&defstream, inLen);
   outBuf = realloc(outBufestimateLen);
   defstream.avail_out = (uInt)estimateLen;
   deflate(&defstream, Z_FINISH);
   deflateEnd(&defstream);

作为一个嵌入式系统,我试图让事情变得简单。

更新2019年2月8日将下面的代码工作(注意Mark的修复):

static uint8_t *compressBuffer(char *inBuf, uint32_t *outLen)
{
   uint32_t inLen = strlen(inBuf)+1;  //  +1 so the null terminator will get encoded
   uint8_t *outBuf = NULL;
   int result;
   uint32_t tmpLen=0;

   // initialize zlib
   z_stream defstream;
   defstream.zalloc    = Z_NULL;
   defstream.zfree     = Z_NULL;
   defstream.opaque    = Z_NULL;
   defstream.avail_in  = inLen;
   defstream.next_in   = (Bytef *)inBuf;
   defstream.avail_out = 0;
   defstream.next_out  = (Bytef *)outBuf;
   if ((result = deflateInit(&defstream, Z_DEFAULT_COMPRESSION)) == Z_OK)
   {
      // calculate actual output length and update structure
      uint32_t  estimateLen = deflateBound(&defstream, inLen);
      outBuf = malloc(estimateLen+10);
      if (outBuf != NULL)
      {
         // update zlib configuration
         defstream.avail_out = (uInt)estimateLen;
         defstream.next_out = (Bytef *)outBuf;

         // do the compression
         deflate(&defstream, Z_FINISH);
         tmpLen = (uint8_t*)defstream.next_out - outBuf;
      }
   }

   // do the followimg regardless of outcome to leave in a good place
   deflateEnd(&defstream);

   // return whatever we have
   *outLen = tmpLen;
   return outBuf;
}
dynamic-memory-allocation zlib
1个回答
0
投票

在这两个例子中,你是不是next_out后设置deflateBound()。你defstream.next_out = (Bytef *)outBuf;后需要malloc()

你不需要做realloc()

© www.soinside.com 2019 - 2024. All rights reserved.