在C ++中对void指针执行算术 [英] Performing arithmetic on a void pointer in C++

查看:133
本文介绍了在C ++中对void指针执行算术的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图对地址执行算术。我需要确保它在一个4字节的字边界。这需要我获得指针的无符号整数表示以执行一些数学。我这样做:

  // memStartAddr的类型为void *(来自外部API函数)
data32 tempAddr = reinterpret_cast< data32>(memStartAddr);
//如果需要,调整指向下一个字边界的指针
tempAddr = wordAlign(tempAddr);
// memStartAddress是类型unsigned char *
的类变量memStartAddress = reinterpret_cast< data8 *>(tempAddr);
//计算由于上述调整而丢失的字节
data32 delta =(tempAddr-reinterpret_cast< data32>(memStartAddress));
//利用整数算术来确保可用大小是4字节的多重
//。剩余内容丢失。如有必要,收缩可用尺寸。
memSize =((size-delta)/ 4)* 4;

这一切都适用于我的测试,但是,使用reinterpret_cast被认为是禁止的做法。有另一种方法吗?

您正在寻找 memStartAddress = std: :align(4,objSize,memStartAddr,objSize + 3); 。标准函数比你需要的更灵活一点,所以你需要告诉它你最多需要一个+3的地址变化。


I am trying to perform arithmetic on an address. I need to make sure that it is on a 4 byte word boundary. This requires me to get an unsigned integer representation of the pointer to perform some math on. I have done this:

//memStartAddr is of type void* (from an external API function)
data32 tempAddr = reinterpret_cast<data32>(memStartAddr);
//adjust pointer to the next word boundary if needed
tempAddr = wordAlign(tempAddr);
//memStartAddress is a class variable of type unsigned char*
memStartAddress = reinterpret_cast<data8*>(tempAddr);
//calculate bytes lost due to above adjustment
data32 delta = (tempAddr - reinterpret_cast<data32>(memStartAddress));
//Take advantage of integer arithmetic to ensure usable size is a multiple
//of 4 bytes. Remainders are lost. Shrinks usable size if necessary.
memSize = ((size - delta) / 4) * 4;

This all works in my tests, however, using reinterpret_cast is considered a forbidden practice. Is there another way to do this? Or is an exception to the rule warranted here?

解决方案

You're looking for memStartAddress = std::align(4, objSize, memStartAddr, objSize+3);. The standard function is a bit more flexible than you need, so you need to tell it that you want at most a +3 change in address.

这篇关于在C ++中对void指针执行算术的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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