Home / Alt manpages / perlcall(1)

  • perlcall(1)
  • User command
  • linux

Call Perl Subroutines Safely from C with perlcall

You will finish with the core pattern for calling a Perl subroutine from C: prepare the Perl stack, select a calling context, invoke the callback, read its results, and release temporary values. The examples match the installed perlcall documentation from Perl 5.38.2, supplied by Ubuntu package perl-doc version 5.38.2-3.2ubuntu0.6.

Allow about 30 minutes if you already work with Perl's C API, or an hour if the stack macros are new to you. You need a C extension or an embedding project that already initialises Perl, plus the Perl development headers and libraries for that project. This guide focuses on the callback boundary, not on starting an embedded interpreter. Read perlxs, perlguts and perlembed alongside it when you need the surrounding setup.

1. Choose the call function

There are four related entry points:

  • call_sv accepts an SV *, so it can call a subroutine reference or a name held in a scalar.
  • call_pv accepts a C string containing a Perl subroutine name, such as "My::Package::run".
  • call_method calls a method name. The class name or object is supplied on the Perl stack.
  • call_argv accepts a subroutine name and a NULL-terminated list of C strings as arguments.

When both call_sv and call_pv fit, prefer call_sv. It handles a subroutine reference without making the name lookup part of the call. Whichever entry point you choose, its return value is a count of result values, while the values themselves are placed on the Perl stack unless you discard them.

Checkpoint

Write down the callback's exact Perl name, its input types, and whether it should run in void, scalar or list context. Those three decisions determine most of the C code that follows.

2. Set up the argument stack

Arguments are pushed onto Perl's stack between PUSHMARK and PUTBACK. A local stack pointer comes from dSP. The temporary values created by newSViv and newSVpv are made mortal, then scoped with ENTER, SAVETMPS, FREETMPS and LEAVE.

This example calls a Perl subroutine named LeftString with a string and an integer. It deliberately discards the return value:

static void
call_LeftString(char *text, int length)
{
    dSP;

    ENTER;
    SAVETMPS;

    PUSHMARK(SP);
    EXTEND(SP, 2);
    PUSHs(sv_2mortal(newSVpv(text, 0)));
    PUSHs(sv_2mortal(newSViv(length)));
    PUTBACK;

    call_pv("LeftString", G_DISCARD);

    FREETMPS;
    LEAVE;
}

The matching Perl code could be:

sub LeftString {
    my ($text, $length) = @_;
    print substr($text, 0, $length), "\n";
}

PUSHMARK(SP) is required even when there are no arguments. It tells Perl where this call's argument range begins. EXTEND reserves stack space, and PUTBACK publishes the local stack pointer before Perl runs. Omitting that last step leaves the arguments invisible to the callback.

Checkpoint

For a void callback, the safe minimum is dSP, PUSHMARK(SP), PUTBACK, the call, and correctly paired temporary cleanup. Do not add G_NOARGS merely because the visible function has no C parameters: use it only when the Perl callback truly receives no arguments.

3. Pick the context explicitly

The context flag is the first part of the bit mask. G_VOID gives the callback void context and returns a count of zero. G_SCALAR is the default and gives scalar context, leaving at most one result on the stack. G_LIST gives list context and leaves every returned value available.

Other flags are ORed with that context:

  • G_DISCARD removes returned values automatically. It is suitable when the callback is used only for its side effects.
  • G_NOARGS avoids creating @_ for a no-argument call. Use it cautiously because a nested callback can otherwise observe an older @_ array.
  • G_EVAL wraps the callback in an eval, allowing C code to inspect $@ instead of the process terminating on die or a missing subroutine.
  • G_KEEPERR is for specialised cleanup, destructor, signal or hook code. It must be used with G_EVAL and turns a trapped error into a warning rather than replacing $@.

Common trap: scalar context does not mean "take the first result". If a Perl subroutine returns a list in scalar context, only its last value is retained. Use G_LIST when the C side needs the complete list.

4. Read one scalar result

After a call that can change the Perl stack, refresh the local pointer with SPAGAIN. Check the returned count before popping anything. This pattern calls a Perl Adder subroutine and reads one integer:

static int
call_Adder(int left, int right)
{
    dSP;
    int count;
    int result;

    ENTER;
    SAVETMPS;

    PUSHMARK(SP);
    EXTEND(SP, 2);
    PUSHs(sv_2mortal(newSViv(left)));
    PUSHs(sv_2mortal(newSViv(right)));
    PUTBACK;

    count = call_pv("Adder", G_SCALAR);
    SPAGAIN;

    if (count != 1)
        croak("Adder returned %d values", count);

    result = POPi;
    PUTBACK;
    FREETMPS;
    LEAVE;
    return result;
}

The Perl side is ordinary:

sub Adder {
    my ($left, $right) = @_;
    $left + $right;
}

The final PUTBACK matters because POPi changes the local pointer. The value returned by call_pv is a contract check, not a prediction. If callback code changes later and returns an unexpected number of values, failing at the boundary is safer than leaving the stack inconsistent.

5. Read a list in reverse stack order

For a list result, call with G_LIST, check the expected count, and pop values from the end towards the beginning. A Perl function returning ($left + $right, $left - $right) puts the difference on top of the stack, so the difference is popped first:

count = call_pv("AddSubtract", G_LIST);
SPAGAIN;

if (count != 2)
    croak("AddSubtract returned %d values", count);

int difference = POPi;
int sum = POPi;
PUTBACK;

For inputs 7 and 4, the two C variables become difference == 3 and sum == 11. Keep the temporary scope around the whole operation, then call FREETMPS and LEAVE as in the previous example.

6. Catch callback failures

Calling an absent subroutine or allowing the callback to execute die can terminate the process unless you include G_EVAL. The flag does not make the call successful: it changes how the failure is reported. After the call, inspect $@ using the normal Perl API, and handle the stack according to the selected context.

With G_EVAL | G_SCALAR, an error reports a count of one and leaves undef on top of the stack. Pop that value after recording the error. With G_EVAL | G_LIST, an error reports zero results. With G_DISCARD, the count is always zero, so use the error variable rather than the count as the failure signal.

Do not use G_KEEPERR as a general error policy. Its purpose is to stop an unrelated cleanup or hook callback from overwriting the surrounding error state. For ordinary application callbacks, G_EVAL plus explicit error handling is the clearer boundary.

7. Verify before shipping the callback

  1. Confirm the callback name and package qualification, then test a deliberately missing name with G_EVAL in a controlled test.
  2. Test zero arguments, one argument and the full expected argument set. This catches accidental reliance on a stale @_ when using G_NOARGS.
  3. Test a scalar return, an empty return and an unexpected list. Check the count before every POP*.
  4. Run the callback more than once in the same process. This exposes missing PUTBACK, SPAGAIN or temporary cleanup that a single call can hide.
  5. Exercise the callback's error path and verify that the host process remains alive and that the Perl stack is balanced afterwards.

There is no system-wide undo command for these calls. They change the interpreter's stack and callback state only while your C code runs. Recovery means stopping the test process, fixing the stack or error-handling code, and rerunning the isolated test. If the callback changes files, starts services or performs other side effects, apply the separate safety controls for that operation.

Done means

  • The C code selects the correct call_* function and context.
  • Arguments are bracketed by PUSHMARK and PUTBACK.
  • Temporary SVs have a matching ENTER/SAVETMPS and FREETMPS/LEAVE scope.
  • SPAGAIN follows every call before the local stack pointer is reused.
  • Return counts and callback errors are checked before values are popped.
  • Repeated, empty-result and failure-path tests leave the Perl stack usable.