从C代码库中对C ++中的unsigned char *进行strchr的微创改变?

我正在尝试将C代码库编译为C ++,调整一些包含。 它在unsigned char指针上使用strchr() ,例如:

 #include  #include  // Cannot modify this file with any non-C-isms, but let's say an include can // be changed (although all things being equal I'd rather not) #include  int main(int argc, char* argv[]) { unsigned char b = 'B'; unsigned char const * str = "ABC"; unsigned char const * pos = strchr(str, b); if (pos) { printf("position is %d\n", pos - str); } return 0; } 

这导致了C ++中的错误(出于其他地方解释的原因)……即使使用-fpermissive也是-fpermissive

 test.c: In function 'int main(int, char**)': test.c:6:33: warning: invalid conversion from 'const char*' to 'const unsigned char*' [-fpermissive] test.c:7:46: error: call of overloaded 'strchr(const unsigned char*&, unsigned char&)' is ambiguous test.c:7:46: note: candidates are: In file included from test.c:1:0: /usr/include/string.h:215:14: note: char* strchr(char*, int)  /usr/include/string.h:215:14: note: no known conversion for argument 1 from 'const unsigned char*' to 'char*' /usr/include/string.h:217:22: note: const char* strchr(const char*, int)  /usr/include/string.h:217:22: note: no known conversion for argument 1 from 'const unsigned char*' to 'const char*' 

通常当面对这种事情时,我会“strchr,yuck,只是完全摆脱它” 。 但我不想自己修改这些文件,这是C代码,它可以保持非常便携,而不是旧平台。 他们不会乐意把演员阵容放在呼吁上来安抚C ++ ……虽然如果一个“struchr”存在并且是标准的,他们可能会使用它。

我也可以用这种或那种方式破解它,比如在SomethingICanChange.h我可以添加:

 unsigned char const * strchr(unsigned char const * s, int c) { return (unsigned char const *)strchr((char const *)s, c); } 

这适用于-fpermissive 。 但我无法检查C代码库中的重载(好吧,没有#ifdef)。 只是想知道是否有人有更好的想法,如果这就是人们在这种情况下最终会做什么(或者如果有一个共同的名称是常见的话),我会推荐添加struchr

初步说明 :我知道这也是一个非常丑陋的事情,但它可能会帮助你(希望)更好的主意!

如何使用宏:

 #define strchr(s, c) ((unsigned char const *)strchr((char const *)s, c)) 

您可以将它作为编译标志(-D)包含在Makefile / build脚本中。 我想你有一个C ++项目的自定义Makefile / build脚本,所以你不需要将这个宏添加到C代码库。

为了使它稍微好一点,您可以使用Makefile / build脚本中包含的附加文件,该文件以(更多)结构化方式将这些宏添加到CPPFLAGS