-1

How to write strings and integers in a ring buffer? I would like to write multiple strings and integers into the ring buffer but my c++ knowledge is limited. If you need some more info, please let me know. I appreciate any help that you can provide.

Here are the integer and string variables that I want to write and the write function of the ring buffer:

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;
}
  • Please elaborate on your question: what is it you want to do? Just call this function with your given inputs? – tnull Dec 05 '14 at 23:40
  • Yes, I can't get the arguments right. I tried with (payload, sizeof(payload)) for example and also many other things but I always get invalid arguments. So my question is how to call the function once for the string and once for the integer. Thank you for your attention to this matter. – g.katsarov Dec 06 '14 at 00:46
  • Is it a "buffer of (strings and numbers)" or a "buffer of (strings or numbers)"? You would use a `struct` or `union`, respectively. The code example shown is quite incomplete and lacks comments on how it is supposed to work. To me it looks much more like some mess (like assembly language using C++ syntax) rather than a ring buffer. – U. Windl Nov 03 '20 at 11:10

2 Answers2

0

You have to convert your std::string variable into a C-style pointer to char:

string payload;
char* cpayload = payload.c_str();
int len = strlen(cpayload);
ringbuffer::write(cpayload, len*sizeof(char));
tnull
  • 728
  • 5
  • 17
  • Invalid arguments Candidates are: unsigned int write(unsigned char *, unsigned int) – g.katsarov Dec 06 '14 at 16:40
  • Then cast the `len`: `unsigned int len = (unsigned int) strlen(cpayload) * sizeof(char)` and use `len` as the second argument. – tnull Dec 07 '14 at 22:24
  • Still not working mate but I think I found out what is the problem. If you are interested you can check my answer, thank you for your attention to this matter. – g.katsarov Dec 08 '14 at 11:39
0

This is what seems to be working but I haven't verified what exactly I am getting in the ringbuffer yet, no errors though.

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