简体   繁体   中英

Casting between SIZE_T and void* on Windows

I have read several posts on stackoverflow such as size_t vs. uintptr_t and Is sizeof(size_t) == sizeof(void*) always true? and understood that per the C++ standard, the sizes of SIZE_T and void* can be different to account for architectures such as 16-bit segmented architectures.

So I'd like to limit the platforms of my scenario to be Windows, whether it's x86, x64, WoA (Windows on Arm): On Windows, if I malloc to create a pointer of type void*, and I want to do pointer-arithmetic before passing it to memcpy or something, I'd have to something like:

void* p = malloc(100);
memcpy(reinterpret_cast<void*>((reinterpret_cast<SIZE_T>(p) + offset), p2, 100);

Which seems very tedious, especially if you have to litter this type of casting back-and-forth everywhere (I am working with various offsets). Given this is on a Windows platform, I wonder if there's some simplifications that can be made to reduce this type of boilerplate code?

Thanks.

将其强制转换为unsigned char *然后使用该指针进行算术运算。

根据您的描述,我认为您只想要:

memcpy( (char *)p + offset, p2, 100);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM