简体   繁体   中英

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.

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")

Issues with char * and unsigned char * are annoying , because (on 2's complement) they all point to the same thing. Even though aliasing via these types is permitted, the C standard requires a diagnostic. Some compilers have an option to suppress diagnostic for this case (when you omit the cast).

You could write some wrappers:

xmlChar *VxmlGetProp(const xmlNode *node, const char *name)
{
    return xmlGetProp(node, (const unsigned char *)name);
}

Note that I didn't write const xmlChar in the cast as this would silently cause broken behaviour if you later reconfigured libxml to use wide characters for xmlChar .

You could even use const void * as the argument type to allow your function to take both const char * , and const unsigned char * .


Another option (which also adds some typo-resistance) to your code would be to not use the string literals in place; instead have them in a table, eg

#define STRING_FOOBAR ((const unsigned char *)"foobar")

and then use STRING_FOOBAR in your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM