in reply to Re^3: XS: Manipulating refcounts
in thread XS: Manipulating refcounts

The standard way of throwing a meaningful error rather than segfaulting when supplied with bad input of the type you describe is to vet arguments using sv_derived_from, which is the perlapi function which implements isa. Manually inserted, such argument checking would look something like this...
/* Constructor for CD. */ SV* new_cd(SV *artist_sv) { if (!sv_derived_from(artist_sv, "Artist") { Croak("Not an Artist"); } Artist *artist = INT2PTR( Artist*, SvIV(SvRV(artist_sv)) ); /* ... */ }

That stops anything but Artist and its subclasses from getting through. If somebody does something like bless a hash into the "Artist" package and submit that we'll still get a segfault, but that's less likely to happen inadvertently.

Typically, the argument-checking code is not typed in manually, but is inserted by xsubpp via a typemap which spares the programmer from the error-prone drudgery of repeating that code over and over.

Rest assured that my production code always implements such checks. I agree that the example code is dangerous. I left out the safety code because the sample was already too long -- long enough to dissuade demerphq from looking at it, for example.

--
Marvin Humphrey
Rectangular Research ― http://www.rectangular.com