in reply to Inline::C callbacks to Perl

Yes, I think it's because in the line:
setCallback( \&calledBack );
the reference to the subroutine is being assigned to a temporary SV, which then goes out of scope (since it doesn't know the C program is still using it).   Then when C tries to use it, the thing it was pointing to is no longer there.

So if you try this instead:

my $psub = \&calledBack; setCallback( $psub );
you should get the results you want, as the subroutine reference now exists in the still persistent, lexically-scoped "$psub" to which the SV "g_callback" points.

It's a really good question.

Replies are listed 'Best First'.
Re^2: Inline::C callbacks to Perl
by Animator (Hermit) on Nov 11, 2005 at 21:40 UTC

    I agree with what [id://liverpole] is saying.

    What is happening is that the SV that is holding the reference gets destroyed. Storing it in a variable leads to the same problem. (When the variable goes out of scope that is).

    The proper way to prevent this from happening is to increase the reference counter of the code-SV. (Since that will prevent the reference counter of the (temp) variable to become 0. Meaning Perl won't destroy it.)

    (You can do this by using SvREFCNT_inc(code);. You can read more about the function/macro in perlapi)

    Update: changed wording

      Spot on, thanks. Incrementing the ref count in setCallback sorted me right out.


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.