I want to wrap a C library, libcookie
, in C++.
Setting
The library has an object-like structure like so
struct Cookie;
typedef struct Cookie COOKIE;
int CookieGetTemperature(COOKIE*);
// ...
COOKIE* CookieGetBest(); // Meant as reference
So I want to wrap it with something like the following:
struct ObjCookie {
COOKIE* ptr;
int getTemperature() { return CookieGetTemperature(ptr); }
};
ObjCookie getBest() {
return {CookieGetBest()};
}
The actual wrapping is not as simple, given return codes, out parameters, etc., which is why I want to provide the wrapping.
Problem
My difficulty comes with arrays of cookies:
COOKIE** CookieGetAll(); // Meant as array of references
int CookieGetNCookies(); // Size of previous array
I'd like to be able to reinterpret the array as a span (like std::span
but third party):
span<ObjCookie> getAll() {
return {reinterpret_cast<ObjCookie*>(CookieGetAll()), CookieGetNCookies()};
}
But I understand that this is undefined behavior.
Is there a way around to make this idea work? Using compiler specific hacks?
Or keep UB with a check like static_assert(sizeof(ObjCookie) == sizeof(COOKIE))
Alternatively, I thought of making a copy, but it can be a bit of performance hit if the array is large and the function called often.
Finally the last option would be to not wrap COOKIE
in ObjCookie
, but only the free functions (CookieGetTemperature
).