Laurent,

Extending the example in perlcall to work for repeated calls to Perl is not
hard, but you have clearly taken the wrong path. In particular, you should
have "dSP;" and "PUSHMARK(SP);" at least once in your code, and I see
you've removed them completely. Sometimes it's just hard to put all the
pieces together, and perhaps the language barrier is causing trouble.

I've included a working solution below that takes a Perl subroutine
(reference, not name) and calls it the requested number of times. It also
prints out some diagnostic output from C so that you can see the flow of
the code. Extending this to take a subroutine name instead of a subref, or
passing arguments, is left as an exercise to the reader. :-)

If you have more questions about XS which perlcall does not explain, you
might consider signing up for perl...@perl.org. It's a very low-volume list
that might be better targeted to your XS questions.

David

use strict;
use warnings;
use Inline 'C';

my $n_times_called = 0;
sub my_perl_func {
    $n_times_called++;
    print "Called ${n_times_called}th time\n";
}

call_from_c(\&my_perl_func, 10);

__DATA__
__C__

void call_from_c(SV * subref, int n_times) {
    int i;
    printf("Starting C function\n");
    for (i = 0; i < n_times; i++) {
        dSP;
        PUSHMARK(SP);
        printf("Calling Perl function...\n");
        call_sv(subref, G_DISCARD|G_NOARGS);
        printf("I'm back\n");
    }
    printf("Done with C function\n");
}

Reply via email to