c++ - 有没有什么好的方法可以把 unsigned char* 转换成 char*?

标签 c++ casting reinterpret-cast

那些日子我读了很多关于 reinterpret_cast<> 的书以及应该如何使用它(并在大多数情况下避免使用它)。

虽然我知道使用 reinterpret_cast<>从,说 unsigned char*char*实现定义(因此不可移植)似乎没有其他方法可以有效将一个转换为另一个。

假设我使用处理 unsigned char* 的库处理一些计算。在内部,我已经使用了 char*存储我的数据(而且我无法更改它,因为如果我这样做会杀死小狗)。

我会做类似的事情:

char* mydata = getMyDataSomewhere();
size_t mydatalen = getMyDataLength();

// We use it here
// processData() takes a unsigned char*
void processData(reinterpret_cast<unsigned char*>(mydata), mydatalen);

// I could have done this:
void processData((unsigned char*)mydata, mydatalen);
// But it would have resulted in a similar call I guess ?

如果我希望我的代码具有高度的可移植性,似乎除了先复制我的数据之外别无选择。像这样的东西:

char* mydata = getMyDataSomewhere();
size_t mydatalen = getMyDataLength();
unsigned char* mydata_copy = new unsigned char[mydatalen];
for (size_t i = 0; i < mydatalen; ++i)
  mydata_copy[i] = static_cast<unsigned char>(mydata[i]);

void processData(mydata_copy, mydatalen);

当然,这是非常次优的,我什至不确定它是否比第一个解决方案更便携。

所以问题是,在这种情况下您会怎么做才能拥有高度可移植的代码?

最佳答案

可移植是一个实践中的问题。因此,reinterpret_cast 用于在 char*unsigned char* 之间转换的具体用法是可移植的。但我仍然将此用法包装在一对函数中,而不是在每个地方直接执行 reinterpret_cast

当使用几乎所有缺陷(包括关于 reinterpret_cast 的有限保证)都支持效率的语言时,不要过度引入低效率。

这将违背语言的精神,同时又遵守文字。

干杯。

关于c++ - 有没有什么好的方法可以把 unsigned char* 转换成 char*?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4708444/

相关文章:

c++ - 我如何使用 opencv 取 100 张图像的平均值?

C++!如何调用析构函数

c - 如何在里面工作 printf ?

php - 在 PHP 中使用 settype 而不是使用括号进行类型转换,有什么区别?

c++ - 有没有办法在没有 reinterpret_cast 的情况下保存多种类型的函数指针?

c++ - BSD 套接字问题 : inet_ntop returning "0.0.0.0"

c# - .NET : Unable to cast object to interface it implements

c++ - 重新解释强制转换为不同类型的C++

c++ - Reinterpret_cast 在 C++ 中的使用

c++ - Apple Blocks 与 C++11 Lambdas