c++ - 从 C 代码库在 C++ 中对 unsigned char * 上的 strchr 进行微创更改?

标签 c++ c unsigned-char strchr

我正在尝试将 C 代码库编译为 C++,调整其中的一些内容。它在无符号字符指针上使用 strchr(),例如:

#include <string.h>
#include <stdio.h>

// 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 <SomethingICanChange.h>

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

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) <near match>
/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) <near match>
/usr/include/string.h:217:22: note:   no known conversion for argument 1 from ‘const unsigned char*’ to ‘const char*’

通常当面对这种事情时,我会“strchr,糟糕,完全摆脱它”。但我不想自己修改这些文件,这是 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))

您可以将其作为 Makefile/build 脚本的编译标志 (-D) 包含在内。我假设您有一个用于 C++ 项目的自定义 Makefile/构建脚本,因此您不需要将此宏添加到 C 代码库。

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

关于c++ - 从 C 代码库在 C++ 中对 unsigned char * 上的 strchr 进行微创更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13906150/

相关文章:

c++ - 如何绘制跟踪对象时的运动?

c++ - 如何在 C 或 C++ 中实现 SDP?

c - 请为 smpd : 指定身份验证密码

arrays - 如何将 const unsigned char 数组中的元素转换为 char

C++ 以 7 位存储数字

c++ - 在 C++、OpenGL 中使用 De Casteljau 算法绘制贝塞尔曲线

c - 从文件读取未知数量的 int 到链表

c++ - 什么类型的转换适合从 unsigned char* 转换为 char*?

C++ 以十六进制检索 Unicode 代码点

c++ - IsDebuggerPresent() 函数是停止调试进程的安全方法吗?