有没有好的方法从unsigned char *转换为char *? [英] Is there a good way to convert from unsigned char* to char*?

查看:3659
本文介绍了有没有好的方法从unsigned char *转换为char *?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读很多关于 reinterpret_cast<> 的日子,以及如何使用它(在大多数情况下避免使用它)。

I've been reading a lot those days about reinterpret_cast<> and how on should use it (and avoid it on most cases).

虽然我明白使用 reinterpret_cast<> 从中强制转换,例如 unsigned char * char * 实现定义(因此非便携式),似乎没有其他方式

While I understand that using reinterpret_cast<> to cast from, say unsigned char* to char* is implementation defined (and thus non-portable) it seems to be no other way for efficiently convert one to the other.

假设我使用一个库来处理 unsigned char * 来处理一些计算。内部,我已经使用 char * 来存储我的数据(我不能改变它,因为它会杀了小狗,如果我做了)。

Lets say I use a library that deals with unsigned char* to process some computations. Internaly, I already use char* to store my data (And I can't change it because it would kill puppies if I did).

我会这样做:

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 ?

如果我想我的代码高度可移植,似乎我没有别的选择,第一。类似:

If I want my code to be highly portable, it seems I have no other choice than copying my data first. Something like:

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

当然,这是非常不理想的,我甚至不确定它比第一个解决方案。

Of course, that is highly suboptimal and I'm not even sure that it is more portable than the first solution.

所以问题是,在这种情况下你会做一个高度可移植的代码?

So the question is, what would you do in this situation to have a highly-portable code ?

推荐答案

Portable是一个实践中的事情。因此, reinterpret_cast 用于在 char * 之间转换的具体用法unsigned char * / code>是可移植的。但是我仍然会把这个用法放在一对函数中,而不是直接在每个地方执行 reinterpret_cast

Portable is an in-practice matter. As such, reinterpret_cast for the specific usage of converting between char* and unsigned char* is portable. But still I'd wrap this usage in a pair of functions instead of doing the reinterpret_cast directly each place.

当使用一种几乎所有疣(包括关于 reinterpret_cast 的有限保证的一种疣)支持效率的时候,不要过分地引入低效率。

Don't go overboard introducing inefficiencies when using a language where nearly all the warts (including the one about limited guarantees for reinterpret_cast) are in support of efficiency.

这将违反语言的精神,同时坚持信。

That would be working against the spirit of the language, while adhering to the letter.

干杯&

这篇关于有没有好的方法从unsigned char *转换为char *?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆