missingthepoint has asked for the wisdom of the Perl Monks concerning the following question:

Greetings, monks.

I've been tinkering with Inline::C recently, and found myself printing error messages from C directly. I consider this bad juju for all but trivial uses of C-in-Perl... So what is the best way to propagate errors at the C level to Perl? I think some of Perl's builtins (the ones which do syscalls?) set $! on error. Can I set this variable from C? Is there a better way to report errors that occur in C code?

Awaiting your wisdom,

mtp


email: perl -e 'print reverse map { chr( ord($_)-1 ) } split //, "\x0bufo/hojsfufqAofc";'

Replies are listed 'Best First'.
Re: Propagating errors in C code to Perl
by betterworld (Curate) on Sep 05, 2008 at 13:42 UTC

    Afaik you can die from C code using the "croak" function. Here's an example how to do it and set $@. Probably setting $! works similar (Update:) by setting errno (see Joost's post).

    If you throw exceptions from C code, you just have to make sure that all your dynamically allocated memory is freed, which can be a problem in callbacks from external libraries.

Re: Propagating errors in C code to Perl
by Joost (Canon) on Sep 05, 2008 at 13:50 UTC
    As betterworld said: you can just croak() from C and it'll throw an exception in the calling perl code. This, or returning undef/false, is almost always what you want to do.

    You can set $! from C, but you should probably only do so under very limited circumstances. $! is tied directly to the C macro errno which is almost exclusively used for IO errors. Look it up. Note that errno is a number.

      Thanks, betterworld and Joost.

      Right now to return undef I'm saying:

      return (SV *) &PL_sv_undef;

      and to return false I'm saying:

      return newSViv(0);

      are these correct? Again, is there a better way to do that?


      email: perl -e 'print reverse map { chr( ord($_)-1 ) } split //, "\x0bufo/hojsfufqAofc";'
Re: Propagating errors in C code to Perl
by sasdrtx (Friar) on Sep 05, 2008 at 22:35 UTC
    Well, I thought this post was going to be about propagating coding errors while translating a program from C to Perl. I have experience doing that. :-)

    missingthepoint as the author makes for nice irony.


    sas

      :)

      I originally chose the nick because I say that phrase all the time... But quickly realised that I'm leaving myself wide open to jokes if I post something silly. Ah, well. :o)


      email: perl -e 'print reverse map { chr( ord($_)-1 ) } split //, "\x0bufo/hojsfufqAofc";'