Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ wrapper for an array of pointers returned from a C function

Tags:

c++

stl

I'm adding a C++ front-end to a C library. One function in this library calls back to a handler with an array and an integer with the size of the array. Therefore you must provide a C function,

int handler(int argc, sometype **argv);

Now, I'd like to allow the C++ calling code to provide a more C++ish handler function, something like,

int handler(std::vector<sometype*> args);

Changing the handler type isn't hard, I just have to provide my own handler which then calls the user-provided handler. So I need to create an std::vector and copy the contents of argv into it.

However, I don't really want to copy the entire list of pointers if possible. Unfortunately I think it's not possible to tell std::vector to use an already-allocated block of memory for its internal array, and moreover the array is static, and should be considered const.

Is there some STL type similar to std::vector that can be used to wrap pre-allocated C-style arrays with a more friendly interface? It should support size query and iteration, similar to std::vector.

Thanks.

like image 380
Steve Avatar asked Dec 04 '25 23:12

Steve


1 Answers

Have you thought about making your function take a pair of iterators instead of a container? You would have to make it a template function, so I can understand why that may not work as well as you would like, but it would let you pass in the array.

template<typename I>
int handler(I begin, I end);

handler(argv, &argv[argc]);

It's still not a perfect solution, but it would be a touch more generic and allow for you to use the preexisting array.

like image 66
Fox Cutter Avatar answered Dec 07 '25 17:12

Fox Cutter



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!