Test if a given object reference is valid

196 views Asked by At

How can I reliably test (in IL or with some methods provided by the .NET) whether a given native int is a valid object reference (O)? The pointer may have been retrieved from some debugger, and it might not be valid (or collected after it was returned). Simply returning it as an object throws uncatchable ExecutionEngineException on invalid addresses. I tried castclass to object, which throws NullPointerException in case of some invalid references, but it also throws bad AccessViolationException with some addresses. Is there a better way to do it, without throwing any uncatchable exceptions or corrupting memory?

1

There are 1 answers

0
Brian Reichle On BEST ANSWER

In a comment on the question, you said the pointer comes from the profiler API, so I'm going to assume that your debugger is implemented using the profiler API.

There is no reliable way to check if a pointer to an object (ObjectID) is valid. Even if it is pointing to what appears to be a valid object, it might not be the same object. Instead, the normal approach is to track the object through the GC callbacks and update/discard your references as appropriate.

If you store the pointer somewhere that isn't updated and the GC is allowed to run, then you should automatically assume the pointer is invalid.