perlperl-xsperlapi

How to get access to current context from XS?


When a user calls XS from main:: package we can not use

caller_cx(0, NULL);

because there is no frames for main:: and for XSUB DOC

Note that XSUBs don't get a stack frame, so C will return information for the immediately-surrounding Perl code

How to get the file:line info the XSUB is called from, hints for main:: scope etc. info?


Solution

  • Copied from mess_sv (called by Perl API functions warn and croak, which append line information like the Perl functions warn and die):

    use strict;
    use warnings;
    use feature qw( say );
    
    use Inline C => <<'__EOS__';
    
    void testing() {
        dXSARGS;
    
        /*
         * Try and find the file and line for PL_op.  This will usually be
         * PL_curcop, but it might be a cop that has been optimised away.  We
         * can try to find such a cop by searching through the optree star ting
         * from the sibling of PL_curcop.
         */
        if (PL_curcop) {
            const COP *cop =
                Perl_closest_cop(aTHX_ PL_curcop, OpSIBLING(PL_curcop), PL_op, FALSE);
            if (!cop)
                cop = PL_curcop;
    
            if (CopLINE(cop)) {
                EXTEND(SP, 2);
                mPUSHs(newSVpv(OutCopFILE(cop), 0));
                mPUSHs(newSViv((IV)CopLINE(cop)));
                XSRETURN(2);
            }
        }
    
        XSRETURN(0);
    }
    
    __EOS__
    
    say join ":", testing();
    

    A little bit about PL_curcop here.