jeudi 26 février 2015

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.


Aucun commentaire:

Enregistrer un commentaire