Shouldn't there be a instanceof here, to verify this is actually a mongo_db zval?
Otherwise the cast will just be random and the later checks may or may not actually work?