简体   繁体   English

一种将字符串文字自动转换为C中的unsigned char *的方法?

[英]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 . 我正在为项目使用libxml2,它的一个怪癖是xmlCharunsigned char的typedef,而不仅仅是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* . 据我所知,这对实际执行没有任何影响,但是使用字符串文字确实很烦人,因为我必须手动将其转换为const xmlChar* All I really want is to be able to write xmlGetProp(node, "some-property") instead of xmlGetProp(node, (const xmlChar*)"some-property") . 我真正想要的是能够编写xmlGetProp(node, "some-property")而不是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. 它可能看起来很小,但是当其他每个语句都具有(const xmlChar*)时,它会使代码变得更加难以阅读。

Is there a way to make const char* cast to const xmlChar* ( const unsigned char* ) without manual casts? 有没有一种方法可以将const char*强制转换为const xmlChar*const unsigned char* )而无需手动强制转换? 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. 我认为这在C ++中会相当容易,但是我对C感到困惑。

libxml2 defines a macro BAD_CAST in xmlstring.h : libxml2的限定宏BAD_CASTxmlstring.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. char *unsigned char *很烦人,因为(在2的补码上)它们都指向同一件事。 Even though aliasing via these types is permitted, the C standard requires a diagnostic. 即使允许通过这些类型进行别名,C标准也需要进行诊断。 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 . 请注意,我没有在类型转换中编写const xmlChar ,因为如果您稍后将libxml重新配置为对xmlChar使用宽字符,这将无提示地导致行为中断。

You could even use const void * as the argument type to allow your function to take both const char * , and const unsigned char * . 您甚至可以使用const void *作为参数类型,以允许您的函数同时使用const char *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. 然后在您的代码中使用STRING_FOOBAR

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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