Search code examples
boostiteratorbuffercircular-buffer

Boost Circular Buffer pointer access (c++)


I would like to use the Boost circular buffer to store arrays that are produced by a hardware API. The API takes in the address of the memory location and pushes the array accordingly. So I have the following:

typedef unsigned char API_data [10];

boost::circular_buffer<API_data> data(10);
boost::circular_buffer<API_data>::iterator it = data.begin();

But I cannot pass the pointer it to the API because:

no suitable conversion function from "boost::cb_details::iterator<boost::circular_buffer<API_data, std::allocator<API_data>>, boost::cb_details::nonconst_traits<boost::container::allocator_traits<std::allocator<API_data>>>>" to LPVOID exists.

The API is expecting a pointer of type LPVOID but it pointer is of different type.


Solution

  • Circular buffer API is similar to ::std::vector API. But there is a catch. First, items stored in circular buffer must be copy assignable so you can not store raw arrays in it. Second, you supply container capacity in constructor, not initial container size so before trying to pass a pointer to stored item you need to make sure that it is there. Pushing into circular buffer may drop oldest items if buffer is full unlike std::vector which will always grow. Then you can get a reference to a pushed item and convert it to pointer to void.

    using API_data_buffer = ::std::array< unsigned char, 10 >;
    
    ::boost::circular_buffer< API_data_buffer > buffers(10); // buffers is still empty!
    buffers.push_back();
    auto & api_data_buffer{buffers.back()};
    auto const p_void_api_data{reinterpret_cast< void * >(reinterpret_cast< ::std::uintptr_t >(api_data_buffer.data()))};