What are the best practices for returning read-only std::vector<uint8_t> by value from C++ API for consumption by C?
// cpplib.hpp
struct A {
std::vector<uint8_t> getHash() const;
};
// c-api.h
typedef struct A A_t;
??? A_get_hash();
// c-api.cpp
extern "C" {
??? A_get_hash() {
// return std::vector<uint8_t> to C here
A a = doSomethingToGetA();
return a.getHash(); ???
}
}
One option that I considered was to define new struct in C representing this vector:
struct vector {
const uint8_t* data;
size_t size;
}
But, as a C++ programmer it hurts to allocate with new then return.
- consumers will forget to deallocate memory for this array
- given many functions, consumers will not know that some returned pointers are read-only (no deallocation needed), and some require deallocation.