in reply to When to (and not to) use sv_2mortal()

A little guidance in the form of a few lines of code illustrating a C subroutine (ala Inline::C) calling a Perl sub and getting an int from its rv would be helpful to me.

The perlcall documentation is your friend for this. It contains good examples - some of which have been used in the Inline-0.48/C/t/10callback.t test script. Here's one of them:
use warnings; use strict; use Inline C => Config => BUILD_NOISY => 1; use Inline C =><<'EOC'; void call_Adder(int a, int b) { dSP; int count; ENTER; SAVETMPS; PUSHMARK(SP); XPUSHs(sv_2mortal(newSViv(a))); XPUSHs(sv_2mortal(newSViv(b))); PUTBACK; count = call_pv("Adder", G_SCALAR); SPAGAIN; if (count != 1) croak("Big trouble\n"); printf ("The sum of %d and %d is %d\n", a, b, POPi); PUTBACK; FREETMPS; LEAVE; } EOC call_Adder(17, 16); sub Adder { my($a, $b) = @_; $a + $b; }
I gather you've already discovered that the Inline::C stack macros are, by themselves, usually incapable of dealing with callbacks.

Cheers,
Rob

Replies are listed 'Best First'.
Re^2: When to (and not to) use sv_2mortal()
by davido (Cardinal) on Oct 29, 2011 at 00:18 UTC

    I gather you've already discovered that the Inline::C stack macros are, by themselves, usually incapable of dealing with callbacks.

    Yes... that's sort of how I got here. I was imagining a situation where I would bury a Perl callback into a C function, either as an iterator or as an actor. Of course it sort of defeats the purpose of inlining C if you're suddenly burying a Perl sub-based iterator into it. But it seemed like higher-order-kinky fun. However a callback as an action could be useful.


    Dave