简体   繁体   中英

Using a 64bit uint for pointer values in 32bit mode?

I am implementing a C-based programming language and I would like to implement a compilation mode that is agnostic to whether it runs in 32bit or 64bit mode. All my datatypes have explicit width, so binary compatibility there is not a problem, the only problematic aspect is pointers.

So what if I go for an explicit 64bit implementation of pointers even under 32bit mode? IIRC pretty much all memory controllers are at least 64bit, so reads and writes will still be a single cycle, but what about integer arithmetic?

Besides the increase of memory footprint, are there any potential drawbacks to such an approach? Any other potential caveats?

Edit: Let me clarify the scenario context - the original question was a little off. I need that "binary agnostic mode" for an interpreter bytecode to be able to dynamically bridge different native binaries. Naturally, there is little to no point of using a pointer from a 64 bit binary in a 32 bit binary, but the width of the pointers affects the offsets for the locations of the other data, which is what will primarily be interchanged. So in short, the idea is the following - waste a bit of space for the sake of making a data structure binary compatible to both 32 and 64 bit binaries.

You can use the uintptr_t type.

It is an unsigned int that is guaranteed to be the same size as a pointer.

Its definition is standard in C++11 and in C99 (use the <stdint.h> header file).

If you want the pointer to be always 64-bit, you can use uint64_t . However, this is unsafe on systems with 128-bit pointers.

It is not the case that 64 bit access is atomic on all 32 bit machines. As for arithmetic, typical 32 bit machines do not have 64 bit arithmetic units and so the compilers implement 64 bit arithmetic using runtime support functions built on top of 32 bit arithmetic units.

I suppose that if you did hold a 32 bit pointers in a 64 bit data type, you would just ignore half of the bits. When running in 32 bit mode you would perform 32 bit operations on the 64 bit pointer. There's clearly no point in performing 64 bit operations when only 32 of the bits have meaning. In which case you'd just have a 32 bit type, stored in a 64 bit slot, with half of the bits wasted.

In light of this, what you are describing seems pointless to me. It seems to me that you have decided that it is desirable for all data types to have the same size irrespective of whether you are on 32 or 64 bit. That may be a desirable goal for some data types, but it's not so for pointers.

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