memcpy返回不正确的结果

时间:2013-12-01 03:26:19

标签: c++ audio

这个测试示例我按预期工作:

FLAC__int32 array[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
FLAC__int32 const *const handle(array);

FLAC__int32 temp[10];
std::vector<FLAC__int32> base;

base.resize(10);
memcpy(&base[0], handle, 10 * sizeof(FLAC__int32));

for (size_t i(0); i < 10; i++)
    cout << endl << "[ " << i << " ] " << base[i];

但是,使用下面的代码,我无法让memcpy正常工作。如何更正此问题,以便memcpy制作正确的缓冲区副本?

Note: _buffer contains binary data which was decoder by libFLAC.

FLAC__StreamDecoderWriteStatus
Source::write_callback
    (FLAC__Frame const* _frame, FLAC__int32 const *const _buffer[])
{

    cout << endl << "Head index [ " << index_ << " ].";

    memcpy(&data_[index_], &_buffer[0], _frame->header.blocksize * 
        sizeof(FLAC__int32));

    index_ += _frame->header.blocksize;
    cout << endl << "Tail index [ " << index_ << " ].";


    for(size_t i(0); i < 400; i++) {

        cout << endl << "Buff [ " << i << " ] " << _buffer[i];
        cout << endl << "Data [ " << i << " ] " << data_[i];

    } // jump

    return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
} // main

以下是我调整矢量大小并重置索引的方法:

void
Source::metadata_callback (const ::FLAC__StreamMetadata *metadata)
{

    ...

    total_samples_ = metadata->data.stream_info.total_samples;

    ...

    data_.resize(total_samples_); index_ = 0;

} // main

1 个答案:

答案 0 :(得分:1)

你想要一个深层拷贝(也就是说,你想复制FLAC__int32值,而不是指向它们的指针),你似乎并不在意你是否构造了这些值或指针的容器对那些价值观。所以memcpy是错误的工具。让我们从一个非常简单的案例开始:

void foo(int * buf)
{
  int data = *buf;
}

然后尝试将数组复制到向量:

void foo(int * buf[])
{
  vector<int> data(10);

  for(unsigned int k=0; k<3; ++k)
    data[k] = *buf[k];
}

然后是完整的解决方案:

FLAC__StreamDecoderWriteStatus Source::write_callback(FLAC__Frame const* _frame, FLAC__int32 const *const _buffer[])
{
  cout << endl << "Head index [ " << index_ << " ].";

  data_.resize(_frame->header.blocksize);
  for(size_t k=0; k<_frame->header.blocksize; ++k)
  {
    data_[index_+k] = *_buffer[k];
  }

  index_ += _frame->header.blocksize;
  cout << endl << "Tail index [ " << index_ << " ].";

  for(size_t i(0); i < 400; i++)
  {
    cout << endl << "Buff [ " << i << " ] " << *_buffer[i];
    cout << endl << "Data [ " << i << " ] " << data_[i];
  }

  return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;                                      
}