2011-02-05 63 views
1
char buffer[12] = {"Testing! 12"}; 

unsigned long compressedSize; 
char* compressed = compress(buffer, 12, &compressedSize); 

... 

char* compress(char* buffer, unsigned long size, unsigned long* compressedSize) 
{ 
    Bytef* inBuffer = reinterpret_cast<Bytef*>(buffer); 
    uLong inSize = static_cast<uLong>(size); 

    Bytef* outBuffer = 0; 
    uLong outBufferSize = compressBound(inSize); 

    int error = compress2(outBuffer, &outBufferSize, inBuffer, inSize, 6); 

    if(error != Z_OK) 
    { 
     switch(error) 
     { 
      case Z_MEM_ERROR: 
       std::cerr << "Memory error!" << std::endl; 
       break; 

      case Z_BUF_ERROR: 
       std::cerr << "Buffer error!" << std::endl; 
       break; 

      default: 
       std::cerr << "Unknown error: " << error << std::endl; 
       break; 
     } 

     return 0; 
    } 

    *compressedSize = static_cast<unsigned long>(outBufferSize); 

    return reinterpret_cast<char*>(outBuffer); 
} 

我打'未知的錯誤:-2'原來是ZLIB_STREAM_ERROR。我無法弄清楚這個問題。所有的變量似乎都是正確的。zlib compress2正在返回Z_STREAM_ERROR

回答

5

outBuffer是一個空指針。您無法將NULL指針作爲輸出緩衝區傳遞到compress2,compress2需要一些空間來存儲壓縮數據,因此請分配一個compressBound(inSize)大的緩衝區。從壓縮原型2中可以明顯看出,你不能將compres2分配並「返回」這樣的緩衝區給你。

編輯,因爲在這一點實際的錯誤是Z_STREAM_ERROR,那是因爲你在一個無效的水平通過。

compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, Z_STREAM_ERROR if the level parameter is invalid.

你應該使用這些級別之一:

#define Z_NO_COMPRESSION   0 
#define Z_BEST_SPEED    1 
#define Z_BEST_COMPRESSION  9 
#define Z_DEFAULT_COMPRESSION (-1) 
+1

它在說什麼http://zlib.net/manual.html#Utility有關。 – Jookia 2011-02-05 21:05:04