Consider a simple, re-usable library. It has a object for the current state, and a callback function to feed it input.
typedef struct Context_S Context_T;
typedef size_t (*GetBytes_T) (Context_T * ctx, uint8_t * bytes, size_t max);
struct Context_S {
GetBytes_T byteFunc;
void * extra;
// more elements
};
void Init(Context_T * ctx, GetBytes_T func);
int GetNext(Context_T * ctx); // Calls callback when needs more bytes
User might need some extra data for callback (like file pointer). Library provides functions to have 1 extra pointer:
void SetExtra(Context_T * ctx, void * ext); // May be called after init
void * GetExtra(Context_T const * ctx); // May be called in callback
However, if user extra data is constant, it would require him to cast constness away before setting the data. I could change the functions to take/return const, but this would require extra cast in callback, if data should not be constant.
void SetExtra(Context_T * ctx, void const * ext);
void const * GetExtra(Context_T const * ctx);
Third alternative would be to hide cast inside the function calls:
void SetExtra(Context_T * ctx, void const * ext);
void * GetExtra(Context_T const * ctx);
Is it good idea to hide cast in this case?
I'm trying to find balance with usability and type safety. But since we are
using void*
pointers, lot of safety is gone already.
Or am I overlooking something worthy of consideration?