Move casting behaviour into own functions, to allow multiple interfaces
Made to_* functions throw exceptions, add try_* functions to return NULL