You cannot safe-cast a pointer. This will fail:
ptr as TProject
You can only cast pointers the unsafe way:
TProject(ptr)
That is, unless you use this neat trick:
TObject(ptr) as TProject
This will also catch programming errors, specifically a pointer that doesn’t point to an object.
"This will also catch programming errors, specifically a pointer that doesn’t point to an object."
ReplyDeleteThat's just nonsense. casting a pointer to an object will only work if the pointer is actually an object pointer.
Try this:
TObject(pointer(-1)) as TComponent
@Anonymous: isn't that what he said? It will catch pointers that don't point to objects.
ReplyDeleteThe example I gave is the best case scenario because it "just" throws an access violation. In real life the outcome of a hard cast on an unknown pointer value will depend on whatever happens to be in memory at that location. It might be an object or it might be random noise that just happens to look like an object.
ReplyDeleteThis is really basic stuff. Hard casting removes the safety of strongly types language. Using the "as" operator on a hard cast will not bring that safety back.
Actually, even if it was "random noise that looks like an object," this would almost certainly catch it. Randomness means it's not 100% certain, of course, but with the way the as-cast works, essentially traversing a linked list of VMTs until it finds one that matches, the odds against "random noise" actually finding a match before either hitting an access violation, a nil, or an infinite loop are astronomically low.
Delete