Mike Spertus said:
Unfortunately, I can't discuss the reason I need it here, but let me
just say that it is a good one that does not ever involve
dereferencing a pointer. Certainly one should be able to think of many
reasons why one might want to know what the stackpointer is. Since I
am only interested in the stackpointer, I'm not really concered
whether objects move around the heap.
In any case, there's nothing inherently unsafe about putting the ESP
register in an int as long as I don't cast it to a pointer, which
would indeed be recognized as unsafe. As far as I can tell, there's no
intrinsic reason one couldn't safely put a register (or the
stackpointer) into an int. However, I haven't found a way to do it.
The compiler will require unsafe to keep you from playing any cute tricks,
like getting the pointer of a local, casting it to int and sending it off to
a method that *does* dereference the pointer value. It is just not
effectivly safe to do.
Now, more to the point, within .NET itself, ESP doesn't exist. It has an
instruction stack and no registers and does not inherently have the concept
of a register. Any assumptions you make as to which variable happens to
match up with the beginning of the stack, or even that ESP points to the
same effective stack that the variable exists on is potentially dangerous.
The stack is abstracted and not guarenteed to exist in any particular manner
or order after the JIT and compiler's run.
I do not think there is any reliable way to get a stack pointer within the
language itself, that seems to be relegated to debuggers and the like.
Unsafe code and accessing the first variable is as close as you are going to
come.