Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting C uint8_t pointer + size combination to C++ iterators

I have some C code that I want to encapsulate in C++ to make it easier to use.

The C code uses a uint8_t*/size_t pair to reference a piece of memory. Can I convert these to C++ iterators with something like std::begin/std::end? I know these functions don't accept pointers, but perhaps there's some other way. I want to avoid having to copy any data.

What I'm looking for is something like this:

void fn(uint8_t* ptr, size_t size) {
    auto begin = std::begin(...);
    auto end = std::end(...);

    // continue to use begin/end similar to std::vector<uint8_t>::iterator
}

The iterators should be usable with the standard library. Specifically I want to use it with std::copy and the std::vector constructor that takes iterators. I know I have other options to copy memory, but I'm looking for encapsulation in C++ types.

I also tried this, but apparently that is a private constructor. (Makes complete sense to me that I can't construct a vector iterator, but I'm just trying things.)

std::vector<uint8_t>::iterator begin(ptr);

I'd also prefer to avoid having to implement my own iterator types.

like image 808
molf Avatar asked Oct 21 '25 14:10

molf


2 Answers

auto begin = ptr;
auto end = ptr+size;

will do the trick
(iterators are actually modelled after pointers)

like image 106
sp2danny Avatar answered Oct 23 '25 03:10

sp2danny


You could simply define the function for example like:)

template <class RandomAccessIterator>
void fn( RandomAccessIterator begin, RandomAccessIterator end ) {

    // continue to use begin/end similar to std::vector<uint8_t>::iterator
}

and call it like

fn( ptr, ptr + size );

Of course you could choice any kind of the iterator that is more appropriate for the function.

like image 38
Vlad from Moscow Avatar answered Oct 23 '25 03:10

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!