Search code examples
ccastinglibxml2string-literals

A way to automatically cast string literals to `unsigned char*` in C?


I'm using libxml2 for a project, and one of its quirks is that xmlChar is a typedef for unsigned char instead of just char. As far as I can tell, that doesn't have any effect on the actual execution, but it makes it really annoying to use string literals since I have to manually cast to const xmlChar*. All I really want is to be able to write xmlGetProp(node, "some-property") instead of xmlGetProp(node, (const xmlChar*)"some-property"). It may seem minor, but it makes the code significantly harder to read when every other statement has a (const xmlChar*) cast.

Is there a way to make const char* cast to const xmlChar* (const unsigned char*) without manual casts? Or alternately, is there a reason I shouldn't do this?

I assume this would be reasonably easy in C++, but I'm stuck with C.


Solution

  • libxml2 defines a macro BAD_CAST in xmlstring.h:

    #define BAD_CAST (xmlChar *)
    

    It can be used like this:

    xmlStrEqual(name, BAD_CAST "xml:lang")