It's said that because libxml2 uses unsigned char
as storage to make encoding/decoding between char sets convenient ---- isn't it ugly to force users to write "BAD_CAST" everywhere in the code, when reading/creating xml node names, contents, text nodes, etc.
It there a way to avoid writing such "BAD_CAST" everywhere? The design is really so bad.
This design decision is unfortunate, but rooted in another unfortunate choice made 40 years ago: allowing char
to be potentially signed by default, which is inconsistent with the behavior of getchar()
, strcmp()
...
You can use an inline function to convert from char *
to unsigned char *
and vice-versa with a single hidden cast, and use these when passing arguments:
static inline unsigned char *c2uc(char *s) { return (unsigned char*)s; }
static inline char *uc2c(unsigned char *s) { return (char*)s; }
These wrappers are much safer to use than basic casts as they can only be applied to one type and convert to its unsigned
counterpart. Regular casts are problematic as they can be applied to any type and hide type conversion errors. static inline
functions are expanded by the compiler at no runtime cost.