如何在环形缓冲区中编写字符串和整数?

时间:2014-12-05 23:25:10

标签: c++ circular-buffer

如何在环形缓冲区中写入字符串和整数?我想在环形缓冲区中写入多个字符串和整数,但我的c ++知识有限。如果您需要更多信息,请告诉我。我感谢您提供的任何帮助。

以下是我要写的整数和字符串变量以及环形缓冲区的写入功能:

string payload;
int byte_pos;

size_t ringbuffer::write(u_char *data, size_t bytes)
{
  if (bytes == 0) return 0;

  size_t capacity = capacity_;
  size_t bytes_to_write = std::min(bytes, capacity - size_);

  // Write in a single step
  if (bytes_to_write <= capacity - end_index_)
  {
    memcpy(data_ + end_index_, data, bytes_to_write);
    end_index_ += bytes_to_write;
    if (end_index_ == capacity) end_index_ = 0;
  }
  // Write in two steps
  else
  {
    size_t size_1 = capacity - end_index_;
    memcpy(data_ + end_index_, data, size_1);
    size_t size_2 = bytes_to_write - size_1;
    memcpy(data_, data + size_1, size_2);
    end_index_ = size_2;
  }

  size_ += bytes_to_write;
  return bytes_to_write;
}

2 个答案:

答案 0 :(得分:0)

您必须将std::string变量转换为指向char的C风格指针:

string payload;
char* cpayload = payload.c_str();
int len = strlen(cpayload);
ringbuffer::write(cpayload, len*sizeof(char));

答案 1 :(得分:0)

这似乎有效,但我还没有确认我在ringbuffer中到底是什么,但没有错误。

ringbuffer::write((u_char*) payload.c_str(), payload.length());
ringbuffer::write((u_char*) &byte_pos, sizeof(byte_pos));