Have two class members point to the same memory address

239 Views Asked by At

I want to have two value-type members of my class point to the same memory address, so that initializing one would initialize the other and changing one would change the other. Alternatively it could be two variables within a function, or, a way to cast a variable or constant value into a different type.

The easiest example of why someone would want this is the classic 0x5F3759DF fast inverse square root, where a float's value is re-read as an int, manipulated, and re-read back into float.

I quite vividly remember reading a blog post demonstrating this, but I can't seem to find it right now. If memory serves, the set-up was similar to this:

class Dummy
{
    // Make these two point to the same memory address, and initializing one would initialize the other
    Int64 a;
    Double b;
}

Or perhaps the two variables were at the beginning of a function. Either way, I really remember that initializing one would automatically initialize the other and using the "uninitialized" one would work without error. Perhaps they were even the same type rather than two different types.

FWIW, I am not currently trying to do this, but rather am wondering about the capabilities of C# to do such a thing.

1

There are 1 best solutions below

0
On

What you want is a contradiction in terms. Value-type values don't point to anything (regardless of whether they're members or not) - only reference-type values do. See here for example.

It seems you are imagining something like what we have in file systems: Several "hard links" can point to the same physical location. But in that case, they're still links - "reference-type values" if you will.

In your example with the manipulation of the float as an integer, you might have something like

struct my_algorithm_state_t {
    float value;
}

void manipulate(my_algorithm_state_t& state) {
    auto reinterpreted_value = reinterpret_cast<int32_t&>(*state.value);
    /* ... do stuff with reinterpreted_value*/
}

or, more simply

void manipulate(my_algorithm_state_t& state) {
    state.value = actually_manipulate(reinterpret_cast<int32_t>(state.value));
}

which would hopefully amount to the same thing.