Improve and harden handling of edge cases in C-API