这个reinterpret_cast是如何工作的? (将 C++ 移植到 Java)
我有一些 C++ 代码正在尝试移植到 Java,如下所示:
struct foostruct {
unsigned char aa : 3;
bool ab : 1;
unsigned char ba : 3;
bool bb : 1;
};
static void foo(const unsigned char* buffer, int length)
{
const unsigned char *end = buffer + length;
while (buffer < end)
{
const foostruct bar = *(reinterpret_cast<const foostruct*>(buffer++));
//read some values from struct and act accordingly
}
}
reinterpret_cast
正在做什么?
I have some C++ code I'm trying to port to Java, that looks like this:
struct foostruct {
unsigned char aa : 3;
bool ab : 1;
unsigned char ba : 3;
bool bb : 1;
};
static void foo(const unsigned char* buffer, int length)
{
const unsigned char *end = buffer + length;
while (buffer < end)
{
const foostruct bar = *(reinterpret_cast<const foostruct*>(buffer++));
//read some values from struct and act accordingly
}
}
What is the reinterpret_cast
doing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它基本上是说当前指针表示的 8 位应该被解释为“foostruct”。
在我看来,最好写成如下:
我认为那时所做的事情要明显得多。我认为您可能会发现通过这种方式移植到 Java 也更容易......
its basically saying the 8 bits represented at the current pointer should be interpreted as a "foostruct".
In my opinion it would be better written as follows:
I think it is far more obvious what is being done then. I think you may well find it easier to port to Java this way too ...
它执行经典 C 风格
(const foostruct *)buffer
在最坏的情况下会执行的操作:告诉 C++ 忽略所有安全性,并且您确实知道自己在做什么。在这种情况下,缓冲区实际上由 foostruct 组成,而这些结构又是覆盖在单个 8 位字符上的位字段。本质上,您可以在 Java 中执行相同的操作,只需获取字节并自行执行移位和掩码操作即可。It does what a classic C-style
(const foostruct *)buffer
would do at worst: tells C++ to ignore all safety and that you really know what you are doing. In this case, that thebuffer
actually consists offoostruct
s, which in turn are bit fields overlain on single 8 bit characters. Essentially, you can do the same in Java by just getting the bytes and doing the shift and mask operations yourself.你有一个指向 unsigned char 的指针吗?现在想象一下,指针指向的位被视为 foostruct 类型的对象。这就是 reinterpret_cast 所做的 - 它将位模式重新解释为另一种类型的内存表示......
you have a pointer to unsigned char right? Now imagine that the bits pointed to by the pointer are treated as though it were an object of type foostruct. That's what reinterpret_cast does - it reinterprets the bit pattern to be a memory representation of another type...