{
    "content": [
        {
            "type": "text",
            "text": "# PERLCALL (man)\n\n## NAME\n\nperlcall - Perl calling conventions from C\n\n## DESCRIPTION\n\nThe purpose of this document is to show you how to call Perl subroutines directly from C,\ni.e., how to write callbacks.\n\n## Sections\n\n- **NAME**\n- **DESCRIPTION**\n- **THE CALL FUNCTIONS**\n- **FLAG VALUES** (1 subsections)\n- **EXAMPLES** (10 subsections)\n- **LIGHTWEIGHT CALLBACKS**\n- **SEE ALSO**\n- **AUTHOR**\n- **DATE**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "PERLCALL",
        "section": "",
        "mode": "man",
        "summary": "perlcall - Perl calling conventions from C",
        "synopsis": null,
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [
            "Enough of the definition talk! Let's have a few examples.",
            "Perl provides many macros to assist in accessing the Perl stack.  Wherever possible, these",
            "macros should always be used when interfacing to Perl internals.  We hope this should make",
            "the code less vulnerable to any changes made to Perl in the future.",
            "Another point worth noting is that in the first series of examples I have made use of only",
            "the callpv function.  This has been done to keep the code simpler and ease you into the",
            "topic.  Wherever possible, if the choice is between using callpv and callsv, you should",
            "always try to use callsv.  See \"Using callsv\" for details.",
            "This first trivial example will call a Perl subroutine, PrintUID, to print out the UID of the",
            "process.",
            "sub PrintUID",
            "print \"UID is $<\\n\";",
            "and here is a C function to call it",
            "static void",
            "callPrintUID()",
            "dSP;",
            "PUSHMARK(SP);",
            "callpv(\"PrintUID\", GDISCARD|GNOARGS);",
            "Simple, eh?",
            "A few points to note about this example:",
            "1.   Ignore \"dSP\" and \"PUSHMARK(SP)\" for now. They will be discussed in the next example.",
            "2.   We aren't passing any parameters to PrintUID so GNOARGS can be specified.",
            "3.   We aren't interested in anything returned from PrintUID, so GDISCARD is specified. Even",
            "if PrintUID was changed to return some value(s), having specified GDISCARD will mean",
            "that they will be wiped by the time control returns from callpv.",
            "4.   As callpv is being used, the Perl subroutine is specified as a C string. In this case",
            "the subroutine name has been 'hard-wired' into the code.",
            "5.   Because we specified GDISCARD, it is not necessary to check the value returned from",
            "callpv. It will always be 0.",
            "Now let's make a slightly more complex example. This time we want to call a Perl subroutine,",
            "\"LeftString\", which will take 2 parameters--a string ($s) and an integer ($n).  The",
            "subroutine will simply print the first $n characters of the string.",
            "So the Perl subroutine would look like this:",
            "sub LeftString",
            "my($s, $n) = @;",
            "print substr($s, 0, $n), \"\\n\";",
            "The C function required to call LeftString would look like this:",
            "static void",
            "callLeftString(a, b)",
            "char * a;",
            "int b;",
            "dSP;",
            "ENTER;",
            "SAVETMPS;",
            "PUSHMARK(SP);",
            "EXTEND(SP, 2);",
            "PUSHs(sv2mortal(newSVpv(a, 0)));",
            "PUSHs(sv2mortal(newSViv(b)));",
            "PUTBACK;",
            "callpv(\"LeftString\", GDISCARD);",
            "FREETMPS;",
            "LEAVE;",
            "Here are a few notes on the C function callLeftString.",
            "1.   Parameters are passed to the Perl subroutine using the Perl stack.  This is the purpose",
            "of the code beginning with the line \"dSP\" and ending with the line \"PUTBACK\".  The \"dSP\"",
            "declares a local copy of the stack pointer.  This local copy should always be accessed",
            "as \"SP\".",
            "2.   If you are going to put something onto the Perl stack, you need to know where to put it.",
            "This is the purpose of the macro \"dSP\"--it declares and initializes a local copy of the",
            "Perl stack pointer.",
            "All the other macros which will be used in this example require you to have used this",
            "macro.",
            "The exception to this rule is if you are calling a Perl subroutine directly from an XSUB",
            "function. In this case it is not necessary to use the \"dSP\" macro explicitly--it will be",
            "declared for you automatically.",
            "3.   Any parameters to be pushed onto the stack should be bracketed by the \"PUSHMARK\" and",
            "\"PUTBACK\" macros.  The purpose of these two macros, in this context, is to count the",
            "number of parameters you are pushing automatically.  Then whenever Perl is creating the",
            "@ array for the subroutine, it knows how big to make it.",
            "The \"PUSHMARK\" macro tells Perl to make a mental note of the current stack pointer. Even",
            "if you aren't passing any parameters (like the example shown in the section \"No",
            "Parameters, Nothing Returned\") you must still call the \"PUSHMARK\" macro before you can",
            "call any of the call* functions--Perl still needs to know that there are no parameters.",
            "The \"PUTBACK\" macro sets the global copy of the stack pointer to be the same as our",
            "local copy. If we didn't do this, callpv wouldn't know where the two parameters we",
            "pushed were--remember that up to now all the stack pointer manipulation we have done is",
            "with our local copy, not the global copy.",
            "4.   Next, we come to EXTEND and PUSHs. This is where the parameters actually get pushed onto",
            "the stack. In this case we are pushing a string and an integer.",
            "Alternatively you can use the XPUSHs() macro, which combines a \"EXTEND(SP, 1)\" and",
            "\"PUSHs()\".  This is less efficient if you're pushing multiple values.",
            "See \"XSUBs and the Argument Stack\" in perlguts for details on how the PUSH macros work.",
            "5.   Because we created temporary values (by means of sv2mortal() calls) we will have to",
            "tidy up the Perl stack and dispose of mortal SVs.",
            "This is the purpose of",
            "ENTER;",
            "SAVETMPS;",
            "at the start of the function, and",
            "FREETMPS;",
            "LEAVE;",
            "at the end. The \"ENTER\"/\"SAVETMPS\" pair creates a boundary for any temporaries we",
            "create.  This means that the temporaries we get rid of will be limited to those which",
            "were created after these calls.",
            "The \"FREETMPS\"/\"LEAVE\" pair will get rid of any values returned by the Perl subroutine",
            "(see next example), plus it will also dump the mortal SVs we have created.  Having",
            "\"ENTER\"/\"SAVETMPS\" at the beginning of the code makes sure that no other mortals are",
            "destroyed.",
            "Think of these macros as working a bit like \"{\" and \"}\" in Perl to limit the scope of",
            "local variables.",
            "See the section \"Using Perl to Dispose of Temporaries\" for details of an alternative to",
            "using these macros.",
            "6.   Finally, LeftString can now be called via the callpv function.  The only flag specified",
            "this time is GDISCARD. Because we are passing 2 parameters to the Perl subroutine this",
            "time, we have not specified GNOARGS.",
            "Now for an example of dealing with the items returned from a Perl subroutine.",
            "Here is a Perl subroutine, Adder, that takes 2 integer parameters and simply returns their",
            "sum.",
            "sub Adder",
            "my($a, $b) = @;",
            "$a + $b;",
            "Because we are now concerned with the return value from Adder, the C function required to",
            "call it is now a bit more complex.",
            "static void",
            "callAdder(a, b)",
            "int a;",
            "int b;",
            "dSP;",
            "int count;",
            "ENTER;",
            "SAVETMPS;",
            "PUSHMARK(SP);",
            "EXTEND(SP, 2);",
            "PUSHs(sv2mortal(newSViv(a)));",
            "PUSHs(sv2mortal(newSViv(b)));",
            "PUTBACK;",
            "count = callpv(\"Adder\", GSCALAR);",
            "SPAGAIN;",
            "if (count != 1)",
            "croak(\"Big trouble\\n\");",
            "printf (\"The sum of %d and %d is %d\\n\", a, b, POPi);",
            "PUTBACK;",
            "FREETMPS;",
            "LEAVE;",
            "Points to note this time are",
            "1.   The only flag specified this time was GSCALAR. That means that the @ array will be",
            "created and that the value returned by Adder will still exist after the call to callpv.",
            "2.   The purpose of the macro \"SPAGAIN\" is to refresh the local copy of the stack pointer.",
            "This is necessary because it is possible that the memory allocated to the Perl stack has",
            "been reallocated during the callpv call.",
            "If you are making use of the Perl stack pointer in your code you must always refresh the",
            "local copy using SPAGAIN whenever you make use of the call* functions or any other Perl",
            "internal function.",
            "3.   Although only a single value was expected to be returned from Adder, it is still good",
            "practice to check the return code from callpv anyway.",
            "Expecting a single value is not quite the same as knowing that there will be one. If",
            "someone modified Adder to return a list and we didn't check for that possibility and",
            "take appropriate action the Perl stack would end up in an inconsistent state. That is",
            "something you really don't want to happen ever.",
            "4.   The \"POPi\" macro is used here to pop the return value from the stack.  In this case we",
            "wanted an integer, so \"POPi\" was used.",
            "Here is the complete list of POP macros available, along with the types they return.",
            "POPs        SV",
            "POPp        pointer (PV)",
            "POPpbytex   pointer to bytes (PV)",
            "POPn        double (NV)",
            "POPi        integer (IV)",
            "POPu        unsigned integer (UV)",
            "POPl        long",
            "POPul       unsigned long",
            "Since these macros have side-effects don't use them as arguments to macros that may",
            "evaluate their argument several times, for example:",
            "/* Bad idea, don't do this */",
            "STRLEN len;",
            "const char *s = SvPV(POPs, len);",
            "Instead, use a temporary:",
            "STRLEN len;",
            "SV *sv = POPs;",
            "const char *s = SvPV(sv, len);",
            "or a macro that guarantees it will evaluate its arguments only once:",
            "STRLEN len;",
            "const char *s = SvPVx(POPs, len);",
            "5.   The final \"PUTBACK\" is used to leave the Perl stack in a consistent state before exiting",
            "the function.  This is necessary because when we popped the return value from the stack",
            "with \"POPi\" it updated only our local copy of the stack pointer.  Remember, \"PUTBACK\"",
            "sets the global stack pointer to be the same as our local copy.",
            "Now, let's extend the previous example to return both the sum of the parameters and the",
            "difference.",
            "Here is the Perl subroutine",
            "sub AddSubtract",
            "my($a, $b) = @;",
            "($a+$b, $a-$b);",
            "and this is the C function",
            "static void",
            "callAddSubtract(a, b)",
            "int a;",
            "int b;",
            "dSP;",
            "int count;",
            "ENTER;",
            "SAVETMPS;",
            "PUSHMARK(SP);",
            "EXTEND(SP, 2);",
            "PUSHs(sv2mortal(newSViv(a)));",
            "PUSHs(sv2mortal(newSViv(b)));",
            "PUTBACK;",
            "count = callpv(\"AddSubtract\", GARRAY);",
            "SPAGAIN;",
            "if (count != 2)",
            "croak(\"Big trouble\\n\");",
            "printf (\"%d - %d = %d\\n\", a, b, POPi);",
            "printf (\"%d + %d = %d\\n\", a, b, POPi);",
            "PUTBACK;",
            "FREETMPS;",
            "LEAVE;",
            "If callAddSubtract is called like this",
            "callAddSubtract(7, 4);",
            "then here is the output",
            "7 - 4 = 3",
            "7 + 4 = 11",
            "Notes",
            "1.   We wanted list context, so GARRAY was used.",
            "2.   Not surprisingly \"POPi\" is used twice this time because we were retrieving 2 values from",
            "the stack. The important thing to note is that when using the \"POP*\" macros they come",
            "off the stack in reverse order.",
            "Say the Perl subroutine in the previous section was called in a scalar context, like this",
            "static void",
            "callAddSubScalar(a, b)",
            "int a;",
            "int b;",
            "dSP;",
            "int count;",
            "int i;",
            "ENTER;",
            "SAVETMPS;",
            "PUSHMARK(SP);",
            "EXTEND(SP, 2);",
            "PUSHs(sv2mortal(newSViv(a)));",
            "PUSHs(sv2mortal(newSViv(b)));",
            "PUTBACK;",
            "count = callpv(\"AddSubtract\", GSCALAR);",
            "SPAGAIN;",
            "printf (\"Items Returned = %d\\n\", count);",
            "for (i = 1; i <= count; ++i)",
            "printf (\"Value %d = %d\\n\", i, POPi);",
            "PUTBACK;",
            "FREETMPS;",
            "LEAVE;",
            "The other modification made is that callAddSubScalar will print the number of items returned",
            "from the Perl subroutine and their value (for simplicity it assumes that they are integer).",
            "So if callAddSubScalar is called",
            "callAddSubScalar(7, 4);",
            "then the output will be",
            "Items Returned = 1",
            "Value 1 = 3",
            "In this case the main point to note is that only the last item in the list is returned from",
            "the subroutine. AddSubtract actually made it back to callAddSubScalar.",
            "It is also possible to return values directly via the parameter list--whether it is actually",
            "desirable to do it is another matter entirely.",
            "The Perl subroutine, Inc, below takes 2 parameters and increments each directly.",
            "sub Inc",
            "++ $[0];",
            "++ $[1];",
            "and here is a C function to call it.",
            "static void",
            "callInc(a, b)",
            "int a;",
            "int b;",
            "dSP;",
            "int count;",
            "SV * sva;",
            "SV * svb;",
            "ENTER;",
            "SAVETMPS;",
            "sva = sv2mortal(newSViv(a));",
            "svb = sv2mortal(newSViv(b));",
            "PUSHMARK(SP);",
            "EXTEND(SP, 2);",
            "PUSHs(sva);",
            "PUSHs(svb);",
            "PUTBACK;",
            "count = callpv(\"Inc\", GDISCARD);",
            "if (count != 0)",
            "croak (\"callInc: expected 0 values from 'Inc', got %d\\n\",",
            "count);",
            "printf (\"%d + 1 = %d\\n\", a, SvIV(sva));",
            "printf (\"%d + 1 = %d\\n\", b, SvIV(svb));",
            "FREETMPS;",
            "LEAVE;",
            "To be able to access the two parameters that were pushed onto the stack after they return",
            "from callpv it is necessary to make a note of their addresses--thus the two variables \"sva\"",
            "and \"svb\".",
            "The reason this is necessary is that the area of the Perl stack which held them will very",
            "likely have been overwritten by something else by the time control returns from callpv.",
            "Using GEVAL",
            "Now an example using GEVAL. Below is a Perl subroutine which computes the difference of its",
            "2 parameters. If this would result in a negative result, the subroutine calls die.",
            "sub Subtract",
            "my ($a, $b) = @;",
            "die \"death can be fatal\\n\" if $a < $b;",
            "$a - $b;",
            "and some C to call it",
            "static void",
            "callSubtract(a, b)",
            "int a;",
            "int b;",
            "dSP;",
            "int count;",
            "SV *errtmp;",
            "ENTER;",
            "SAVETMPS;",
            "PUSHMARK(SP);",
            "EXTEND(SP, 2);",
            "PUSHs(sv2mortal(newSViv(a)));",
            "PUSHs(sv2mortal(newSViv(b)));",
            "PUTBACK;",
            "count = callpv(\"Subtract\", GEVAL|GSCALAR);",
            "SPAGAIN;",
            "/* Check the eval first */",
            "errtmp = ERRSV;",
            "if (SvTRUE(errtmp))",
            "printf (\"Uh oh - %s\\n\", SvPVnolen(errtmp));",
            "POPs;",
            "else",
            "if (count != 1)",
            "croak(\"callSubtract: wanted 1 value from 'Subtract', got %d\\n\",",
            "count);",
            "printf (\"%d - %d = %d\\n\", a, b, POPi);",
            "PUTBACK;",
            "FREETMPS;",
            "LEAVE;",
            "If callSubtract is called thus",
            "callSubtract(4, 5)",
            "the following will be printed",
            "Uh oh - death can be fatal",
            "Notes",
            "1.   We want to be able to catch the die so we have used the GEVAL flag.  Not specifying",
            "this flag would mean that the program would terminate immediately at the die statement",
            "in the subroutine Subtract.",
            "2.   The code",
            "errtmp = ERRSV;",
            "if (SvTRUE(errtmp))",
            "printf (\"Uh oh - %s\\n\", SvPVnolen(errtmp));",
            "POPs;",
            "is the direct equivalent of this bit of Perl",
            "print \"Uh oh - $@\\n\" if $@;",
            "\"PLerrgv\" is a perl global of type \"GV *\" that points to the symbol table entry",
            "containing the error.  \"ERRSV\" therefore refers to the C equivalent of $@.  We use a",
            "local temporary, \"errtmp\", since \"ERRSV\" is a macro that calls a function, and",
            "\"SvTRUE(ERRSV)\" would end up calling that function multiple times.",
            "3.   Note that the stack is popped using \"POPs\" in the block where \"SvTRUE(errtmp)\" is true.",
            "This is necessary because whenever a call* function invoked with GEVAL|GSCALAR",
            "returns an error, the top of the stack holds the value undef. Because we want the",
            "program to continue after detecting this error, it is essential that the stack be tidied",
            "up by removing the undef.",
            "Using GKEEPERR",
            "Consider this rather facetious example, where we have used an XS version of the callSubtract",
            "example above inside a destructor:",
            "package Foo;",
            "sub new { bless {}, $[0] }",
            "sub Subtract {",
            "my($a,$b) = @;",
            "die \"death can be fatal\" if $a < $b;",
            "$a - $b;",
            "sub DESTROY { callSubtract(5, 4); }",
            "sub foo { die \"foo dies\"; }",
            "package main;",
            "my $foo = Foo->new;",
            "eval { $foo->foo };",
            "print \"Saw: $@\" if $@;             # should be, but isn't",
            "This example will fail to recognize that an error occurred inside the \"eval {}\".  Here's why:",
            "the callSubtract code got executed while perl was cleaning up temporaries when exiting the",
            "outer braced block, and because callSubtract is implemented with callpv using the GEVAL",
            "flag, it promptly reset $@.  This results in the failure of the outermost test for $@, and",
            "thereby the failure of the error trap.",
            "Appending the GKEEPERR flag, so that the callpv call in callSubtract reads:",
            "count = callpv(\"Subtract\", GEVAL|GSCALAR|GKEEPERR);",
            "will preserve the error and restore reliable error handling.",
            "Using callsv",
            "In all the previous examples I have 'hard-wired' the name of the Perl subroutine to be called",
            "from C.  Most of the time though, it is more convenient to be able to specify the name of the",
            "Perl subroutine from within the Perl script, and you'll want to use callsv.",
            "Consider the Perl code below",
            "sub fred",
            "print \"Hello there\\n\";",
            "CallSubPV(\"fred\");",
            "Here is a snippet of XSUB which defines CallSubPV.",
            "void",
            "CallSubPV(name)",
            "char *  name",
            "CODE:",
            "PUSHMARK(SP);",
            "callpv(name, GDISCARD|GNOARGS);",
            "That is fine as far as it goes. The thing is, the Perl subroutine can be specified as only a",
            "string, however, Perl allows references to subroutines and anonymous subroutines.  This is",
            "where callsv is useful.",
            "The code below for CallSubSV is identical to CallSubPV except that the \"name\" parameter is",
            "now defined as an SV* and we use callsv instead of callpv.",
            "void",
            "CallSubSV(name)",
            "SV *    name",
            "CODE:",
            "PUSHMARK(SP);",
            "callsv(name, GDISCARD|GNOARGS);",
            "Because we are using an SV to call fred the following can all be used:",
            "CallSubSV(\"fred\");",
            "CallSubSV(\\&fred);",
            "$ref = \\&fred;",
            "CallSubSV($ref);",
            "CallSubSV( sub { print \"Hello there\\n\" } );",
            "As you can see, callsv gives you much greater flexibility in how you can specify the Perl",
            "subroutine.",
            "You should note that, if it is necessary to store the SV (\"name\" in the example above) which",
            "corresponds to the Perl subroutine so that it can be used later in the program, it not enough",
            "just to store a copy of the pointer to the SV. Say the code above had been like this:",
            "static SV * rememberSub;",
            "void",
            "SaveSub1(name)",
            "SV *    name",
            "CODE:",
            "rememberSub = name;",
            "void",
            "CallSavedSub1()",
            "CODE:",
            "PUSHMARK(SP);",
            "callsv(rememberSub, GDISCARD|GNOARGS);",
            "The reason this is wrong is that, by the time you come to use the pointer \"rememberSub\" in",
            "\"CallSavedSub1\", it may or may not still refer to the Perl subroutine that was recorded in",
            "\"SaveSub1\".  This is particularly true for these cases:",
            "SaveSub1(\\&fred);",
            "CallSavedSub1();",
            "SaveSub1( sub { print \"Hello there\\n\" } );",
            "CallSavedSub1();",
            "By the time each of the \"SaveSub1\" statements above has been executed, the SV*s which",
            "corresponded to the parameters will no longer exist.  Expect an error message from Perl of",
            "the form",
            "Can't use an undefined value as a subroutine reference at ...",
            "for each of the \"CallSavedSub1\" lines.",
            "Similarly, with this code",
            "$ref = \\&fred;",
            "SaveSub1($ref);",
            "$ref = 47;",
            "CallSavedSub1();",
            "you can expect one of these messages (which you actually get is dependent on the version of",
            "Perl you are using)",
            "Not a CODE reference at ...",
            "Undefined subroutine &main::47 called ...",
            "The variable $ref may have referred to the subroutine \"fred\" whenever the call to \"SaveSub1\"",
            "was made but by the time \"CallSavedSub1\" gets called it now holds the number 47. Because we",
            "saved only a pointer to the original SV in \"SaveSub1\", any changes to $ref will be tracked by",
            "the pointer \"rememberSub\". This means that whenever \"CallSavedSub1\" gets called, it will",
            "attempt to execute the code which is referenced by the SV* \"rememberSub\".  In this case",
            "though, it now refers to the integer 47, so expect Perl to complain loudly.",
            "A similar but more subtle problem is illustrated with this code:",
            "$ref = \\&fred;",
            "SaveSub1($ref);",
            "$ref = \\&joe;",
            "CallSavedSub1();",
            "This time whenever \"CallSavedSub1\" gets called it will execute the Perl subroutine \"joe\"",
            "(assuming it exists) rather than \"fred\" as was originally requested in the call to",
            "\"SaveSub1\".",
            "To get around these problems it is necessary to take a full copy of the SV.  The code below",
            "shows \"SaveSub2\" modified to do that.",
            "/* this isn't thread-safe */",
            "static SV * keepSub = (SV*)NULL;",
            "void",
            "SaveSub2(name)",
            "SV *    name",
            "CODE:",
            "/* Take a copy of the callback */",
            "if (keepSub == (SV*)NULL)",
            "/* First time, so create a new SV */",
            "keepSub = newSVsv(name);",
            "else",
            "/* Been here before, so overwrite */",
            "SvSetSV(keepSub, name);",
            "void",
            "CallSavedSub2()",
            "CODE:",
            "PUSHMARK(SP);",
            "callsv(keepSub, GDISCARD|GNOARGS);",
            "To avoid creating a new SV every time \"SaveSub2\" is called, the function first checks to see",
            "if it has been called before.  If not, then space for a new SV is allocated and the reference",
            "to the Perl subroutine \"name\" is copied to the variable \"keepSub\" in one operation using",
            "\"newSVsv\".  Thereafter, whenever \"SaveSub2\" is called, the existing SV, \"keepSub\", is",
            "overwritten with the new value using \"SvSetSV\".",
            "Note: using a static or global variable to store the SV isn't thread-safe.  You can either",
            "use the \"MYCXT\" mechanism documented in \"Safely Storing Static Data in XS\" in perlxs which",
            "is fast, or store the values in perl global variables, using getsv(), which is much slower.",
            "Using callargv",
            "Here is a Perl subroutine which prints whatever parameters are passed to it.",
            "sub PrintList",
            "my(@list) = @;",
            "foreach (@list) { print \"$\\n\" }",
            "And here is an example of callargv which will call PrintList.",
            "static char * words[] = {\"alpha\", \"beta\", \"gamma\", \"delta\", NULL};",
            "static void",
            "callPrintList()",
            "callargv(\"PrintList\", GDISCARD, words);",
            "Note that it is not necessary to call \"PUSHMARK\" in this instance.  This is because callargv",
            "will do it for you.",
            "Using callmethod",
            "Consider the following Perl code:",
            "package Mine;",
            "sub new",
            "my($type) = shift;",
            "bless [@]",
            "sub Display",
            "my ($self, $index) = @;",
            "print \"$index: $$self[$index]\\n\";",
            "sub PrintID",
            "my($class) = @;",
            "print \"This is Class $class version 1.0\\n\";",
            "It implements just a very simple class to manage an array.  Apart from the constructor,",
            "\"new\", it declares methods, one static and one virtual. The static method, \"PrintID\", prints",
            "out simply the class name and a version number. The virtual method, \"Display\", prints out a",
            "single element of the array.  Here is an all-Perl example of using it.",
            "$a = Mine->new('red', 'green', 'blue');",
            "$a->Display(1);",
            "Mine->PrintID;",
            "will print",
            "1: green",
            "This is Class Mine version 1.0",
            "Calling a Perl method from C is fairly straightforward. The following things are required:",
            "•    A reference to the object for a virtual method or the name of the class for a static",
            "method",
            "•    The name of the method",
            "•    Any other parameters specific to the method",
            "Here is a simple XSUB which illustrates the mechanics of calling both the \"PrintID\" and",
            "\"Display\" methods from C.",
            "void",
            "callMethod(ref, method, index)",
            "SV *    ref",
            "char *  method",
            "int             index",
            "CODE:",
            "PUSHMARK(SP);",
            "EXTEND(SP, 2);",
            "PUSHs(ref);",
            "PUSHs(sv2mortal(newSViv(index)));",
            "PUTBACK;",
            "callmethod(method, GDISCARD);",
            "void",
            "callPrintID(class, method)",
            "char *  class",
            "char *  method",
            "CODE:",
            "PUSHMARK(SP);",
            "XPUSHs(sv2mortal(newSVpv(class, 0)));",
            "PUTBACK;",
            "callmethod(method, GDISCARD);",
            "So the methods \"PrintID\" and \"Display\" can be invoked like this:",
            "$a = Mine->new('red', 'green', 'blue');",
            "callMethod($a, 'Display', 1);",
            "callPrintID('Mine', 'PrintID');",
            "The only thing to note is that, in both the static and virtual methods, the method name is",
            "not passed via the stack--it is used as the first parameter to callmethod.",
            "Using GIMMEV",
            "Here is a trivial XSUB which prints the context in which it is currently executing.",
            "void",
            "PrintContext()",
            "CODE:",
            "U8 gimme = GIMMEV;",
            "if (gimme == GVOID)",
            "printf (\"Context is Void\\n\");",
            "else if (gimme == GSCALAR)",
            "printf (\"Context is Scalar\\n\");",
            "else",
            "printf (\"Context is Array\\n\");",
            "And here is some Perl to test it.",
            "PrintContext;",
            "$a = PrintContext;",
            "@a = PrintContext;",
            "The output from that will be",
            "Context is Void",
            "Context is Scalar",
            "Context is Array",
            "In the examples given to date, any temporaries created in the callback (i.e., parameters",
            "passed on the stack to the call* function or values returned via the stack) have been freed",
            "by one of these methods:",
            "•    Specifying the GDISCARD flag with call*",
            "•    Explicitly using the \"ENTER\"/\"SAVETMPS\"--\"FREETMPS\"/\"LEAVE\" pairing",
            "There is another method which can be used, namely letting Perl do it for you automatically",
            "whenever it regains control after the callback has terminated.  This is done by simply not",
            "using the",
            "ENTER;",
            "SAVETMPS;",
            "...",
            "FREETMPS;",
            "LEAVE;",
            "sequence in the callback (and not, of course, specifying the GDISCARD flag).",
            "If you are going to use this method you have to be aware of a possible memory leak which can",
            "arise under very specific circumstances.  To explain these circumstances you need to know a",
            "bit about the flow of control between Perl and the callback routine.",
            "The examples given at the start of the document (an error handler and an event driven",
            "program) are typical of the two main sorts of flow control that you are likely to encounter",
            "with callbacks.  There is a very important distinction between them, so pay attention.",
            "In the first example, an error handler, the flow of control could be as follows.  You have",
            "created an interface to an external library.  Control can reach the external library like",
            "this",
            "perl --> XSUB --> external library",
            "Whilst control is in the library, an error condition occurs. You have previously set up a",
            "Perl callback to handle this situation, so it will get executed. Once the callback has",
            "finished, control will drop back to Perl again.  Here is what the flow of control will be",
            "like in that situation",
            "perl --> XSUB --> external library",
            "...",
            "error occurs",
            "...",
            "external library --> call* --> perl",
            "perl <-- XSUB <-- external library <-- call* <----+",
            "After processing of the error using call* is completed, control reverts back to Perl more or",
            "less immediately.",
            "In the diagram, the further right you go the more deeply nested the scope is.  It is only",
            "when control is back with perl on the extreme left of the diagram that you will have dropped",
            "back to the enclosing scope and any temporaries you have left hanging around will be freed.",
            "In the second example, an event driven program, the flow of control will be more like this",
            "perl --> XSUB --> event handler",
            "...",
            "event handler --> call* --> perl",
            "event handler <-- call* <----+",
            "...",
            "event handler --> call* --> perl",
            "event handler <-- call* <----+",
            "...",
            "event handler --> call* --> perl",
            "event handler <-- call* <----+",
            "In this case the flow of control can consist of only the repeated sequence",
            "event handler --> call* --> perl",
            "for practically the complete duration of the program.  This means that control may never drop",
            "back to the surrounding scope in Perl at the extreme left.",
            "So what is the big problem? Well, if you are expecting Perl to tidy up those temporaries for",
            "you, you might be in for a long wait.  For Perl to dispose of your temporaries, control must",
            "drop back to the enclosing scope at some stage.  In the event driven scenario that may never",
            "happen.  This means that, as time goes on, your program will create more and more",
            "temporaries, none of which will ever be freed. As each of these temporaries consumes some",
            "memory your program will eventually consume all the available memory in your system--kapow!",
            "So here is the bottom line--if you are sure that control will revert back to the enclosing",
            "Perl scope fairly quickly after the end of your callback, then it isn't absolutely necessary",
            "to dispose explicitly of any temporaries you may have created. Mind you, if you are at all",
            "uncertain about what to do, it doesn't do any harm to tidy up anyway.",
            "Potentially one of the trickiest problems to overcome when designing a callback interface can",
            "be figuring out how to store the mapping between the C callback function and the Perl",
            "equivalent.",
            "To help understand why this can be a real problem first consider how a callback is set up in",
            "an all C environment.  Typically a C API will provide a function to register a callback.",
            "This will expect a pointer to a function as one of its parameters.  Below is a call to a",
            "hypothetical function \"registerfatal\" which registers the C function to get called when a",
            "fatal error occurs.",
            "registerfatal(cb1);",
            "The single parameter \"cb1\" is a pointer to a function, so you must have defined \"cb1\" in your",
            "code, say something like this",
            "static void",
            "cb1()",
            "printf (\"Fatal Error\\n\");",
            "exit(1);",
            "Now change that to call a Perl subroutine instead",
            "static SV * callback = (SV*)NULL;",
            "static void",
            "cb1()",
            "dSP;",
            "PUSHMARK(SP);",
            "/* Call the Perl sub to process the callback */",
            "callsv(callback, GDISCARD);",
            "void",
            "registerfatal(fn)",
            "SV *    fn",
            "CODE:",
            "/* Remember the Perl sub */",
            "if (callback == (SV*)NULL)",
            "callback = newSVsv(fn);",
            "else",
            "SvSetSV(callback, fn);",
            "/* register the callback with the external library */",
            "registerfatal(cb1);",
            "where the Perl equivalent of \"registerfatal\" and the callback it registers, \"pcb1\", might",
            "look like this",
            "# Register the sub pcb1",
            "registerfatal(\\&pcb1);",
            "sub pcb1",
            "die \"I'm dying...\\n\";",
            "The mapping between the C callback and the Perl equivalent is stored in the global variable",
            "\"callback\".",
            "This will be adequate if you ever need to have only one callback registered at any time. An",
            "example could be an error handler like the code sketched out above. Remember though, repeated",
            "calls to \"registerfatal\" will replace the previously registered callback function with the",
            "new one.",
            "Say for example you want to interface to a library which allows asynchronous file i/o.  In",
            "this case you may be able to register a callback whenever a read operation has completed. To",
            "be of any use we want to be able to call separate Perl subroutines for each file that is",
            "opened.  As it stands, the error handler example above would not be adequate as it allows",
            "only a single callback to be defined at any time. What we require is a means of storing the",
            "mapping between the opened file and the Perl subroutine we want to be called for that file.",
            "Say the i/o library has a function \"asynchread\" which associates a C function \"ProcessRead\"",
            "with a file handle \"fh\"--this assumes that it has also provided some routine to open the file",
            "and so obtain the file handle.",
            "asynchread(fh, ProcessRead)",
            "This may expect the C ProcessRead function of this form",
            "void",
            "ProcessRead(fh, buffer)",
            "int fh;",
            "char *      buffer;",
            "...",
            "To provide a Perl interface to this library we need to be able to map between the \"fh\"",
            "parameter and the Perl subroutine we want called.  A hash is a convenient mechanism for",
            "storing this mapping.  The code below shows a possible implementation",
            "static HV * Mapping = (HV*)NULL;",
            "void",
            "asynchread(fh, callback)",
            "int     fh",
            "SV *    callback",
            "CODE:",
            "/* If the hash doesn't already exist, create it */",
            "if (Mapping == (HV*)NULL)",
            "Mapping = newHV();",
            "/* Save the fh -> callback mapping */",
            "hvstore(Mapping, (char*)&fh, sizeof(fh), newSVsv(callback), 0);",
            "/* Register with the C Library */",
            "asynchread(fh, asynchreadif);",
            "and \"asynchreadif\" could look like this",
            "static void",
            "asynchreadif(fh, buffer)",
            "int fh;",
            "char *      buffer;",
            "dSP;",
            "SV  sv;",
            "/* Get the callback associated with fh */",
            "sv =  hvfetch(Mapping, (char*)&fh , sizeof(fh), FALSE);",
            "if (sv == (SV)NULL)",
            "croak(\"Internal error...\\n\");",
            "PUSHMARK(SP);",
            "EXTEND(SP, 2);",
            "PUSHs(sv2mortal(newSViv(fh)));",
            "PUSHs(sv2mortal(newSVpv(buffer, 0)));",
            "PUTBACK;",
            "/* Call the Perl sub */",
            "callsv(*sv, GDISCARD);",
            "For completeness, here is \"asynchclose\".  This shows how to remove the entry from the hash",
            "\"Mapping\".",
            "void",
            "asynchclose(fh)",
            "int     fh",
            "CODE:",
            "/* Remove the entry from the hash */",
            "(void) hvdelete(Mapping, (char*)&fh, sizeof(fh), GDISCARD);",
            "/* Now call the real asynchclose */",
            "asynchclose(fh);",
            "So the Perl interface would look like this",
            "sub callback1",
            "my($handle, $buffer) = @;",
            "# Register the Perl callback",
            "asynchread($fh, \\&callback1);",
            "asynchclose($fh);",
            "The mapping between the C callback and Perl is stored in the global hash \"Mapping\" this time.",
            "Using a hash has the distinct advantage that it allows an unlimited number of callbacks to be",
            "registered.",
            "What if the interface provided by the C callback doesn't contain a parameter which allows the",
            "file handle to Perl subroutine mapping?  Say in the asynchronous i/o package, the callback",
            "function gets passed only the \"buffer\" parameter like this",
            "void",
            "ProcessRead(buffer)",
            "char *      buffer;",
            "...",
            "Without the file handle there is no straightforward way to map from the C callback to the",
            "Perl subroutine.",
            "In this case a possible way around this problem is to predefine a series of C functions to",
            "act as the interface to Perl, thus",
            "#define MAXCB              3",
            "#define NULLHANDLE -1",
            "typedef void (*FnMap)();",
            "struct MapStruct {",
            "FnMap    Function;",
            "SV *     PerlSub;",
            "int      Handle;",
            "};",
            "static void  fn1();",
            "static void  fn2();",
            "static void  fn3();",
            "static struct MapStruct Map [MAXCB] =",
            "{ fn1, NULL, NULLHANDLE },",
            "{ fn2, NULL, NULLHANDLE },",
            "{ fn3, NULL, NULLHANDLE }",
            "};",
            "static void",
            "Pcb(index, buffer)",
            "int index;",
            "char * buffer;",
            "dSP;",
            "PUSHMARK(SP);",
            "XPUSHs(sv2mortal(newSVpv(buffer, 0)));",
            "PUTBACK;",
            "/* Call the Perl sub */",
            "callsv(Map[index].PerlSub, GDISCARD);",
            "static void",
            "fn1(buffer)",
            "char * buffer;",
            "Pcb(0, buffer);",
            "static void",
            "fn2(buffer)",
            "char * buffer;",
            "Pcb(1, buffer);",
            "static void",
            "fn3(buffer)",
            "char * buffer;",
            "Pcb(2, buffer);",
            "void",
            "arrayasynchread(fh, callback)",
            "int             fh",
            "SV *    callback",
            "CODE:",
            "int index;",
            "int nullindex = MAXCB;",
            "/* Find the same handle or an empty entry */",
            "for (index = 0; index < MAXCB; ++index)",
            "if (Map[index].Handle == fh)",
            "break;",
            "if (Map[index].Handle == NULLHANDLE)",
            "nullindex = index;",
            "if (index == MAXCB && nullindex == MAXCB)",
            "croak (\"Too many callback functions registered\\n\");",
            "if (index == MAXCB)",
            "index = nullindex;",
            "/* Save the file handle */",
            "Map[index].Handle = fh;",
            "/* Remember the Perl sub */",
            "if (Map[index].PerlSub == (SV*)NULL)",
            "Map[index].PerlSub = newSVsv(callback);",
            "else",
            "SvSetSV(Map[index].PerlSub, callback);",
            "asynchread(fh, Map[index].Function);",
            "void",
            "arrayasynchclose(fh)",
            "int     fh",
            "CODE:",
            "int index;",
            "/* Find the file handle */",
            "for (index = 0; index < MAXCB; ++ index)",
            "if (Map[index].Handle == fh)",
            "break;",
            "if (index == MAXCB)",
            "croak (\"could not close fh %d\\n\", fh);",
            "Map[index].Handle = NULLHANDLE;",
            "SvREFCNTdec(Map[index].PerlSub);",
            "Map[index].PerlSub = (SV*)NULL;",
            "asynchclose(fh);",
            "In this case the functions \"fn1\", \"fn2\", and \"fn3\" are used to remember the Perl subroutine",
            "to be called. Each of the functions holds a separate hard-wired index which is used in the",
            "function \"Pcb\" to access the \"Map\" array and actually call the Perl subroutine.",
            "There are some obvious disadvantages with this technique.",
            "Firstly, the code is considerably more complex than with the previous example.",
            "Secondly, there is a hard-wired limit (in this case 3) to the number of callbacks that can",
            "exist simultaneously. The only way to increase the limit is by modifying the code to add more",
            "functions and then recompiling.  None the less, as long as the number of functions is chosen",
            "with some care, it is still a workable solution and in some cases is the only one available.",
            "To summarize, here are a number of possible methods for you to consider for storing the",
            "mapping between C and the Perl callback",
            "1. Ignore the problem - Allow only 1 callback",
            "For a lot of situations, like interfacing to an error handler, this may be a perfectly",
            "adequate solution.",
            "2. Create a sequence of callbacks - hard wired limit",
            "If it is impossible to tell from the parameters passed back from the C callback what the",
            "context is, then you may need to create a sequence of C callback interface functions,",
            "and store pointers to each in an array.",
            "3. Use a parameter to map to the Perl callback",
            "A hash is an ideal mechanism to store the mapping between C and Perl.",
            "Although I have made use of only the \"POP*\" macros to access values returned from Perl",
            "subroutines, it is also possible to bypass these macros and read the stack using the \"ST\"",
            "macro (See perlxs for a full description of the \"ST\" macro).",
            "Most of the time the \"POP*\" macros should be adequate; the main problem with them is that",
            "they force you to process the returned values in sequence. This may not be the most suitable",
            "way to process the values in some cases. What we want is to be able to access the stack in a",
            "random order. The \"ST\" macro as used when coding an XSUB is ideal for this purpose.",
            "The code below is the example given in the section \"Returning a List of Values\" recoded to",
            "use \"ST\" instead of \"POP*\".",
            "static void",
            "callAddSubtract2(a, b)",
            "int a;",
            "int b;",
            "dSP;",
            "I32 ax;",
            "int count;",
            "ENTER;",
            "SAVETMPS;",
            "PUSHMARK(SP);",
            "EXTEND(SP, 2);",
            "PUSHs(sv2mortal(newSViv(a)));",
            "PUSHs(sv2mortal(newSViv(b)));",
            "PUTBACK;",
            "count = callpv(\"AddSubtract\", GARRAY);",
            "SPAGAIN;",
            "SP -= count;",
            "ax = (SP - PLstackbase) + 1;",
            "if (count != 2)",
            "croak(\"Big trouble\\n\");",
            "printf (\"%d + %d = %d\\n\", a, b, SvIV(ST(0)));",
            "printf (\"%d - %d = %d\\n\", a, b, SvIV(ST(1)));",
            "PUTBACK;",
            "FREETMPS;",
            "LEAVE;",
            "Notes",
            "1.   Notice that it was necessary to define the variable \"ax\".  This is because the \"ST\"",
            "macro expects it to exist.  If we were in an XSUB it would not be necessary to define",
            "\"ax\" as it is already defined for us.",
            "2.   The code",
            "SPAGAIN;",
            "SP -= count;",
            "ax = (SP - PLstackbase) + 1;",
            "sets the stack up so that we can use the \"ST\" macro.",
            "3.   Unlike the original coding of this example, the returned values are not accessed in",
            "reverse order.  So ST(0) refers to the first value returned by the Perl subroutine and",
            "\"ST(count-1)\" refers to the last.",
            "As we've already shown, \"callsv\" can be used to invoke an anonymous subroutine.  However,",
            "our example showed a Perl script invoking an XSUB to perform this operation.  Let's see how",
            "it can be done inside our C code:",
            "...",
            "SV *cvrv",
            "= evalpv(\"sub {",
            "print 'You will not find me cluttering any namespace!'",
            "}\", TRUE);",
            "...",
            "callsv(cvrv, GVOID|GNOARGS);",
            "\"evalpv\" is used to compile the anonymous subroutine, which will be the return value as well",
            "(read more about \"evalpv\" in \"evalpv\" in perlapi).  Once this code reference is in hand, it",
            "can be mixed in with all the previous examples we've shown."
        ],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "DESCRIPTION",
                "lines": 32,
                "subsections": []
            },
            {
                "name": "THE CALL FUNCTIONS",
                "lines": 54,
                "subsections": []
            },
            {
                "name": "FLAG VALUES",
                "lines": 162,
                "subsections": [
                    {
                        "name": "Determining the Context",
                        "lines": 8
                    }
                ]
            },
            {
                "name": "EXAMPLES",
                "lines": 11,
                "subsections": [
                    {
                        "name": "No Parameters, Nothing Returned",
                        "lines": 37
                    },
                    {
                        "name": "Passing Parameters",
                        "lines": 109
                    },
                    {
                        "name": "Returning a Scalar",
                        "lines": 103
                    },
                    {
                        "name": "Returning a List of Values",
                        "lines": 62
                    },
                    {
                        "name": "Returning a List in Scalar Context",
                        "lines": 48
                    },
                    {
                        "name": "Returning Data from Perl via the Parameter List",
                        "lines": 467
                    },
                    {
                        "name": "Using Perl to Dispose of Temporaries",
                        "lines": 89
                    },
                    {
                        "name": "Strategies for Storing Callback Context Information",
                        "lines": 325
                    },
                    {
                        "name": "Alternate Stack Manipulation",
                        "lines": 65
                    },
                    {
                        "name": "Creating and Calling an Anonymous Subroutine in C",
                        "lines": 19
                    }
                ]
            },
            {
                "name": "LIGHTWEIGHT CALLBACKS",
                "lines": 34,
                "subsections": []
            },
            {
                "name": "SEE ALSO",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "AUTHOR",
                "lines": 6,
                "subsections": []
            },
            {
                "name": "DATE",
                "lines": 5,
                "subsections": []
            }
        ],
        "sections": {
            "NAME": {
                "content": "perlcall - Perl calling conventions from C\n",
                "subsections": []
            },
            "DESCRIPTION": {
                "content": "The purpose of this document is to show you how to call Perl subroutines directly from C,\ni.e., how to write callbacks.\n\nApart from discussing the C interface provided by Perl for writing callbacks the document\nuses a series of examples to show how the interface actually works in practice.  In addition\nsome techniques for coding callbacks are covered.\n\nExamples where callbacks are necessary include\n\n•    An Error Handler\n\nYou have created an XSUB interface to an application's C API.\n\nA fairly common feature in applications is to allow you to define a C function that will\nbe called whenever something nasty occurs. What we would like is to be able to specify a\nPerl subroutine that will be called instead.\n\n•    An Event-Driven Program\n\nThe classic example of where callbacks are used is when writing an event driven program,\nsuch as for an X11 application.  In this case you register functions to be called\nwhenever specific events occur, e.g., a mouse button is pressed, the cursor moves into a\nwindow or a menu item is selected.\n\nAlthough the techniques described here are applicable when embedding Perl in a C program,\nthis is not the primary goal of this document.  There are other details that must be\nconsidered and are specific to embedding Perl. For details on embedding Perl in C refer to\nperlembed.\n\nBefore you launch yourself head first into the rest of this document, it would be a good idea\nto have read the following two documents--perlxs and perlguts.\n",
                "subsections": []
            },
            "THE CALL FUNCTIONS": {
                "content": "Although this stuff is easier to explain using examples, you first need be aware of a few\nimportant definitions.\n\nPerl has a number of C functions that allow you to call Perl subroutines.  They are\n\nI32 callsv(SV* sv, I32 flags);\nI32 callpv(char *subname, I32 flags);\nI32 callmethod(char *methname, I32 flags);\nI32 callargv(char *subname, I32 flags, char argv);\n\nThe key function is callsv.  All the other functions are fairly simple wrappers which make\nit easier to call Perl subroutines in special cases. At the end of the day they will all call\ncallsv to invoke the Perl subroutine.\n\nAll the call* functions have a \"flags\" parameter which is used to pass a bit mask of options\nto Perl.  This bit mask operates identically for each of the functions.  The settings\navailable in the bit mask are discussed in \"FLAG VALUES\".\n\nEach of the functions will now be discussed in turn.\n\ncallsv\ncallsv takes two parameters. The first, \"sv\", is an SV*.  This allows you to specify\nthe Perl subroutine to be called either as a C string (which has first been converted to\nan SV) or a reference to a subroutine. The section, \"Using callsv\", shows how you can\nmake use of callsv.\n\ncallpv\nThe function, callpv, is similar to callsv except it expects its first parameter to be\na C char* which identifies the Perl subroutine you want to call, e.g., \"callpv(\"fred\",\n0)\".  If the subroutine you want to call is in another package, just include the package\nname in the string, e.g., \"pkg::fred\".\n\ncallmethod\nThe function callmethod is used to call a method from a Perl class.  The parameter\n\"methname\" corresponds to the name of the method to be called.  Note that the class that\nthe method belongs to is passed on the Perl stack rather than in the parameter list.\nThis class can be either the name of the class (for a static method) or a reference to\nan object (for a virtual method).  See perlobj for more information on static and\nvirtual methods and \"Using callmethod\" for an example of using callmethod.\n\ncallargv\ncallargv calls the Perl subroutine specified by the C string stored in the \"subname\"\nparameter. It also takes the usual \"flags\" parameter.  The final parameter, \"argv\",\nconsists of a NULL-terminated list of C strings to be passed as parameters to the Perl\nsubroutine.  See \"Using callargv\".\n\nAll the functions return an integer. This is a count of the number of items returned by the\nPerl subroutine. The actual items returned by the subroutine are stored on the Perl stack.\n\nAs a general rule you should always check the return value from these functions.  Even if you\nare expecting only a particular number of values to be returned from the Perl subroutine,\nthere is nothing to stop someone from doing something unexpected--don't say you haven't been\nwarned.\n",
                "subsections": []
            },
            "FLAG VALUES": {
                "content": "The \"flags\" parameter in all the call* functions is one of \"GVOID\", \"GSCALAR\", or\n\"GARRAY\", which indicate the call context, OR'ed together with a bit mask of any combination\nof the other G* symbols defined below.\n\nGVOID\nCalls the Perl subroutine in a void context.\n\nThis flag has 2 effects:\n\n1.   It indicates to the subroutine being called that it is executing in a void context (if\nit executes wantarray the result will be the undefined value).\n\n2.   It ensures that nothing is actually returned from the subroutine.\n\nThe value returned by the call* function indicates how many items have been returned by the\nPerl subroutine--in this case it will be 0.\n\nGSCALAR\nCalls the Perl subroutine in a scalar context.  This is the default context flag setting for\nall the call* functions.\n\nThis flag has 2 effects:\n\n1.   It indicates to the subroutine being called that it is executing in a scalar context (if\nit executes wantarray the result will be false).\n\n2.   It ensures that only a scalar is actually returned from the subroutine.  The subroutine\ncan, of course,  ignore the wantarray and return a list anyway. If so, then only the\nlast element of the list will be returned.\n\nThe value returned by the call* function indicates how many items have been returned by the\nPerl subroutine - in this case it will be either 0 or 1.\n\nIf 0, then you have specified the GDISCARD flag.\n\nIf 1, then the item actually returned by the Perl subroutine will be stored on the Perl stack\n- the section \"Returning a Scalar\" shows how to access this value on the stack.  Remember\nthat regardless of how many items the Perl subroutine returns, only the last one will be\naccessible from the stack - think of the case where only one value is returned as being a\nlist with only one element.  Any other items that were returned will not exist by the time\ncontrol returns from the call* function.  The section \"Returning a List in Scalar Context\"\nshows an example of this behavior.\n\nGARRAY\nCalls the Perl subroutine in a list context.\n\nAs with GSCALAR, this flag has 2 effects:\n\n1.   It indicates to the subroutine being called that it is executing in a list context (if\nit executes wantarray the result will be true).\n\n2.   It ensures that all items returned from the subroutine will be accessible when control\nreturns from the call* function.\n\nThe value returned by the call* function indicates how many items have been returned by the\nPerl subroutine.\n\nIf 0, then you have specified the GDISCARD flag.\n\nIf not 0, then it will be a count of the number of items returned by the subroutine. These\nitems will be stored on the Perl stack.  The section \"Returning a List of Values\" gives an\nexample of using the GARRAY flag and the mechanics of accessing the returned items from the\nPerl stack.\n\nGDISCARD\nBy default, the call* functions place the items returned from by the Perl subroutine on the\nstack.  If you are not interested in these items, then setting this flag will make Perl get\nrid of them automatically for you.  Note that it is still possible to indicate a context to\nthe Perl subroutine by using either GSCALAR or GARRAY.\n\nIf you do not set this flag then it is very important that you make sure that any temporaries\n(i.e., parameters passed to the Perl subroutine and values returned from the subroutine) are\ndisposed of yourself.  The section \"Returning a Scalar\" gives details of how to dispose of\nthese temporaries explicitly and the section \"Using Perl to Dispose of Temporaries\" discusses\nthe specific circumstances where you can ignore the problem and let Perl deal with it for\nyou.\n\nGNOARGS\nWhenever a Perl subroutine is called using one of the call* functions, it is assumed by\ndefault that parameters are to be passed to the subroutine.  If you are not passing any\nparameters to the Perl subroutine, you can save a bit of time by setting this flag.  It has\nthe effect of not creating the @ array for the Perl subroutine.\n\nAlthough the functionality provided by this flag may seem straightforward, it should be used\nonly if there is a good reason to do so.  The reason for being cautious is that, even if you\nhave specified the GNOARGS flag, it is still possible for the Perl subroutine that has been\ncalled to think that you have passed it parameters.\n\nIn fact, what can happen is that the Perl subroutine you have called can access the @ array\nfrom a previous Perl subroutine.  This will occur when the code that is executing the call*\nfunction has itself been called from another Perl subroutine. The code below illustrates this\n\nsub fred\n{ print \"@\\n\"  }\n\nsub joe\n{ &fred }\n\n&joe(1,2,3);\n\nThis will print\n\n1 2 3\n\nWhat has happened is that \"fred\" accesses the @ array which belongs to \"joe\".\n\nGEVAL\nIt is possible for the Perl subroutine you are calling to terminate abnormally, e.g., by\ncalling die explicitly or by not actually existing.  By default, when either of these events\noccurs, the process will terminate immediately.  If you want to trap this type of event,\nspecify the GEVAL flag.  It will put an eval { } around the subroutine call.\n\nWhenever control returns from the call* function you need to check the $@ variable as you\nwould in a normal Perl script.\n\nThe value returned from the call* function is dependent on what other flags have been\nspecified and whether an error has occurred.  Here are all the different cases that can\noccur:\n\n•    If the call* function returns normally, then the value returned is as specified in the\nprevious sections.\n\n•    If GDISCARD is specified, the return value will always be 0.\n\n•    If GARRAY is specified and an error has occurred, the return value will always be 0.\n\n•    If GSCALAR is specified and an error has occurred, the return value will be 1 and the\nvalue on the top of the stack will be undef. This means that if you have already\ndetected the error by checking $@ and you want the program to continue, you must\nremember to pop the undef from the stack.\n\nSee \"Using GEVAL\" for details on using GEVAL.\n\nGKEEPERR\nUsing the GEVAL flag described above will always set $@: clearing it if there was no error,\nand setting it to describe the error if there was an error in the called code.  This is what\nyou want if your intention is to handle possible errors, but sometimes you just want to trap\nerrors and stop them interfering with the rest of the program.\n\nThis scenario will mostly be applicable to code that is meant to be called from within\ndestructors, asynchronous callbacks, and signal handlers.  In such situations, where the code\nbeing called has little relation to the surrounding dynamic context, the main program needs\nto be insulated from errors in the called code, even if they can't be handled intelligently.\nIt may also be useful to do this with code for \"DIE\" or \"WARN\" hooks, and \"tie\"\nfunctions.\n\nThe GKEEPERR flag is meant to be used in conjunction with GEVAL in call* functions that\nare used to implement such code, or with \"evalsv\".  This flag has no effect on the \"call*\"\nfunctions when GEVAL is not used.\n\nWhen GKEEPERR is used, any error in the called code will terminate the call as usual, and\nthe error will not propagate beyond the call (as usual for GEVAL), but it will not go into\n$@.  Instead the error will be converted into a warning, prefixed with the string \"\\t(in\ncleanup)\".  This can be disabled using \"no warnings 'misc'\".  If there is no error, $@ will\nnot be cleared.\n\nNote that the GKEEPERR flag does not propagate into inner evals; these may still set $@.\n\nThe GKEEPERR flag was introduced in Perl version 5.002.\n\nSee \"Using GKEEPERR\" for an example of a situation that warrants the use of this flag.\n",
                "subsections": [
                    {
                        "name": "Determining the Context",
                        "content": "As mentioned above, you can determine the context of the currently executing subroutine in\nPerl with wantarray.  The equivalent test can be made in C by using the \"GIMMEV\" macro,\nwhich returns \"GARRAY\" if you have been called in a list context, \"GSCALAR\" if in a scalar\ncontext, or \"GVOID\" if in a void context (i.e., the return value will not be used).  An\nolder version of this macro is called \"GIMME\"; in a void context it returns \"GSCALAR\"\ninstead of \"GVOID\".  An example of using the \"GIMMEV\" macro is shown in section \"Using\nGIMMEV\".\n"
                    }
                ]
            },
            "EXAMPLES": {
                "content": "Enough of the definition talk! Let's have a few examples.\n\nPerl provides many macros to assist in accessing the Perl stack.  Wherever possible, these\nmacros should always be used when interfacing to Perl internals.  We hope this should make\nthe code less vulnerable to any changes made to Perl in the future.\n\nAnother point worth noting is that in the first series of examples I have made use of only\nthe callpv function.  This has been done to keep the code simpler and ease you into the\ntopic.  Wherever possible, if the choice is between using callpv and callsv, you should\nalways try to use callsv.  See \"Using callsv\" for details.\n",
                "subsections": [
                    {
                        "name": "No Parameters, Nothing Returned",
                        "content": "This first trivial example will call a Perl subroutine, PrintUID, to print out the UID of the\nprocess.\n\nsub PrintUID\n{\nprint \"UID is $<\\n\";\n}\n\nand here is a C function to call it\n\nstatic void\ncallPrintUID()\n{\ndSP;\n\nPUSHMARK(SP);\ncallpv(\"PrintUID\", GDISCARD|GNOARGS);\n}\n\nSimple, eh?\n\nA few points to note about this example:\n\n1.   Ignore \"dSP\" and \"PUSHMARK(SP)\" for now. They will be discussed in the next example.\n\n2.   We aren't passing any parameters to PrintUID so GNOARGS can be specified.\n\n3.   We aren't interested in anything returned from PrintUID, so GDISCARD is specified. Even\nif PrintUID was changed to return some value(s), having specified GDISCARD will mean\nthat they will be wiped by the time control returns from callpv.\n\n4.   As callpv is being used, the Perl subroutine is specified as a C string. In this case\nthe subroutine name has been 'hard-wired' into the code.\n\n5.   Because we specified GDISCARD, it is not necessary to check the value returned from\ncallpv. It will always be 0.\n"
                    },
                    {
                        "name": "Passing Parameters",
                        "content": "Now let's make a slightly more complex example. This time we want to call a Perl subroutine,\n\"LeftString\", which will take 2 parameters--a string ($s) and an integer ($n).  The\nsubroutine will simply print the first $n characters of the string.\n\nSo the Perl subroutine would look like this:\n\nsub LeftString\n{\nmy($s, $n) = @;\nprint substr($s, 0, $n), \"\\n\";\n}\n\nThe C function required to call LeftString would look like this:\n\nstatic void\ncallLeftString(a, b)\nchar * a;\nint b;\n{\ndSP;\n\nENTER;\nSAVETMPS;\n\nPUSHMARK(SP);\nEXTEND(SP, 2);\nPUSHs(sv2mortal(newSVpv(a, 0)));\nPUSHs(sv2mortal(newSViv(b)));\nPUTBACK;\n\ncallpv(\"LeftString\", GDISCARD);\n\nFREETMPS;\nLEAVE;\n}\n\nHere are a few notes on the C function callLeftString.\n\n1.   Parameters are passed to the Perl subroutine using the Perl stack.  This is the purpose\nof the code beginning with the line \"dSP\" and ending with the line \"PUTBACK\".  The \"dSP\"\ndeclares a local copy of the stack pointer.  This local copy should always be accessed\nas \"SP\".\n\n2.   If you are going to put something onto the Perl stack, you need to know where to put it.\nThis is the purpose of the macro \"dSP\"--it declares and initializes a local copy of the\nPerl stack pointer.\n\nAll the other macros which will be used in this example require you to have used this\nmacro.\n\nThe exception to this rule is if you are calling a Perl subroutine directly from an XSUB\nfunction. In this case it is not necessary to use the \"dSP\" macro explicitly--it will be\ndeclared for you automatically.\n\n3.   Any parameters to be pushed onto the stack should be bracketed by the \"PUSHMARK\" and\n\"PUTBACK\" macros.  The purpose of these two macros, in this context, is to count the\nnumber of parameters you are pushing automatically.  Then whenever Perl is creating the\n@ array for the subroutine, it knows how big to make it.\n\nThe \"PUSHMARK\" macro tells Perl to make a mental note of the current stack pointer. Even\nif you aren't passing any parameters (like the example shown in the section \"No\nParameters, Nothing Returned\") you must still call the \"PUSHMARK\" macro before you can\ncall any of the call* functions--Perl still needs to know that there are no parameters.\n\nThe \"PUTBACK\" macro sets the global copy of the stack pointer to be the same as our\nlocal copy. If we didn't do this, callpv wouldn't know where the two parameters we\npushed were--remember that up to now all the stack pointer manipulation we have done is\nwith our local copy, not the global copy.\n\n4.   Next, we come to EXTEND and PUSHs. This is where the parameters actually get pushed onto\nthe stack. In this case we are pushing a string and an integer.\n\nAlternatively you can use the XPUSHs() macro, which combines a \"EXTEND(SP, 1)\" and\n\"PUSHs()\".  This is less efficient if you're pushing multiple values.\n\nSee \"XSUBs and the Argument Stack\" in perlguts for details on how the PUSH macros work.\n\n5.   Because we created temporary values (by means of sv2mortal() calls) we will have to\ntidy up the Perl stack and dispose of mortal SVs.\n\nThis is the purpose of\n\nENTER;\nSAVETMPS;\n\nat the start of the function, and\n\nFREETMPS;\nLEAVE;\n\nat the end. The \"ENTER\"/\"SAVETMPS\" pair creates a boundary for any temporaries we\ncreate.  This means that the temporaries we get rid of will be limited to those which\nwere created after these calls.\n\nThe \"FREETMPS\"/\"LEAVE\" pair will get rid of any values returned by the Perl subroutine\n(see next example), plus it will also dump the mortal SVs we have created.  Having\n\"ENTER\"/\"SAVETMPS\" at the beginning of the code makes sure that no other mortals are\ndestroyed.\n\nThink of these macros as working a bit like \"{\" and \"}\" in Perl to limit the scope of\nlocal variables.\n\nSee the section \"Using Perl to Dispose of Temporaries\" for details of an alternative to\nusing these macros.\n\n6.   Finally, LeftString can now be called via the callpv function.  The only flag specified\nthis time is GDISCARD. Because we are passing 2 parameters to the Perl subroutine this\ntime, we have not specified GNOARGS.\n"
                    },
                    {
                        "name": "Returning a Scalar",
                        "content": "Now for an example of dealing with the items returned from a Perl subroutine.\n\nHere is a Perl subroutine, Adder, that takes 2 integer parameters and simply returns their\nsum.\n\nsub Adder\n{\nmy($a, $b) = @;\n$a + $b;\n}\n\nBecause we are now concerned with the return value from Adder, the C function required to\ncall it is now a bit more complex.\n\nstatic void\ncallAdder(a, b)\nint a;\nint b;\n{\ndSP;\nint count;\n\nENTER;\nSAVETMPS;\n\nPUSHMARK(SP);\nEXTEND(SP, 2);\nPUSHs(sv2mortal(newSViv(a)));\nPUSHs(sv2mortal(newSViv(b)));\nPUTBACK;\n\ncount = callpv(\"Adder\", GSCALAR);\n\nSPAGAIN;\n\nif (count != 1)\ncroak(\"Big trouble\\n\");\n\nprintf (\"The sum of %d and %d is %d\\n\", a, b, POPi);\n\nPUTBACK;\nFREETMPS;\nLEAVE;\n}\n\nPoints to note this time are\n\n1.   The only flag specified this time was GSCALAR. That means that the @ array will be\ncreated and that the value returned by Adder will still exist after the call to callpv.\n\n2.   The purpose of the macro \"SPAGAIN\" is to refresh the local copy of the stack pointer.\nThis is necessary because it is possible that the memory allocated to the Perl stack has\nbeen reallocated during the callpv call.\n\nIf you are making use of the Perl stack pointer in your code you must always refresh the\nlocal copy using SPAGAIN whenever you make use of the call* functions or any other Perl\ninternal function.\n\n3.   Although only a single value was expected to be returned from Adder, it is still good\npractice to check the return code from callpv anyway.\n\nExpecting a single value is not quite the same as knowing that there will be one. If\nsomeone modified Adder to return a list and we didn't check for that possibility and\ntake appropriate action the Perl stack would end up in an inconsistent state. That is\nsomething you really don't want to happen ever.\n\n4.   The \"POPi\" macro is used here to pop the return value from the stack.  In this case we\nwanted an integer, so \"POPi\" was used.\n\nHere is the complete list of POP macros available, along with the types they return.\n\nPOPs        SV\nPOPp        pointer (PV)\nPOPpbytex   pointer to bytes (PV)\nPOPn        double (NV)\nPOPi        integer (IV)\nPOPu        unsigned integer (UV)\nPOPl        long\nPOPul       unsigned long\n\nSince these macros have side-effects don't use them as arguments to macros that may\nevaluate their argument several times, for example:\n\n/* Bad idea, don't do this */\nSTRLEN len;\nconst char *s = SvPV(POPs, len);\n\nInstead, use a temporary:\n\nSTRLEN len;\nSV *sv = POPs;\nconst char *s = SvPV(sv, len);\n\nor a macro that guarantees it will evaluate its arguments only once:\n\nSTRLEN len;\nconst char *s = SvPVx(POPs, len);\n\n5.   The final \"PUTBACK\" is used to leave the Perl stack in a consistent state before exiting\nthe function.  This is necessary because when we popped the return value from the stack\nwith \"POPi\" it updated only our local copy of the stack pointer.  Remember, \"PUTBACK\"\nsets the global stack pointer to be the same as our local copy.\n"
                    },
                    {
                        "name": "Returning a List of Values",
                        "content": "Now, let's extend the previous example to return both the sum of the parameters and the\ndifference.\n\nHere is the Perl subroutine\n\nsub AddSubtract\n{\nmy($a, $b) = @;\n($a+$b, $a-$b);\n}\n\nand this is the C function\n\nstatic void\ncallAddSubtract(a, b)\nint a;\nint b;\n{\ndSP;\nint count;\n\nENTER;\nSAVETMPS;\n\nPUSHMARK(SP);\nEXTEND(SP, 2);\nPUSHs(sv2mortal(newSViv(a)));\nPUSHs(sv2mortal(newSViv(b)));\nPUTBACK;\n\ncount = callpv(\"AddSubtract\", GARRAY);\n\nSPAGAIN;\n\nif (count != 2)\ncroak(\"Big trouble\\n\");\n\nprintf (\"%d - %d = %d\\n\", a, b, POPi);\nprintf (\"%d + %d = %d\\n\", a, b, POPi);\n\nPUTBACK;\nFREETMPS;\nLEAVE;\n}\n\nIf callAddSubtract is called like this\n\ncallAddSubtract(7, 4);\n\nthen here is the output\n\n7 - 4 = 3\n7 + 4 = 11\n\nNotes\n\n1.   We wanted list context, so GARRAY was used.\n\n2.   Not surprisingly \"POPi\" is used twice this time because we were retrieving 2 values from\nthe stack. The important thing to note is that when using the \"POP*\" macros they come\noff the stack in reverse order.\n"
                    },
                    {
                        "name": "Returning a List in Scalar Context",
                        "content": "Say the Perl subroutine in the previous section was called in a scalar context, like this\n\nstatic void\ncallAddSubScalar(a, b)\nint a;\nint b;\n{\ndSP;\nint count;\nint i;\n\nENTER;\nSAVETMPS;\n\nPUSHMARK(SP);\nEXTEND(SP, 2);\nPUSHs(sv2mortal(newSViv(a)));\nPUSHs(sv2mortal(newSViv(b)));\nPUTBACK;\n\ncount = callpv(\"AddSubtract\", GSCALAR);\n\nSPAGAIN;\n\nprintf (\"Items Returned = %d\\n\", count);\n\nfor (i = 1; i <= count; ++i)\nprintf (\"Value %d = %d\\n\", i, POPi);\n\nPUTBACK;\nFREETMPS;\nLEAVE;\n}\n\nThe other modification made is that callAddSubScalar will print the number of items returned\nfrom the Perl subroutine and their value (for simplicity it assumes that they are integer).\nSo if callAddSubScalar is called\n\ncallAddSubScalar(7, 4);\n\nthen the output will be\n\nItems Returned = 1\nValue 1 = 3\n\nIn this case the main point to note is that only the last item in the list is returned from\nthe subroutine. AddSubtract actually made it back to callAddSubScalar.\n"
                    },
                    {
                        "name": "Returning Data from Perl via the Parameter List",
                        "content": "It is also possible to return values directly via the parameter list--whether it is actually\ndesirable to do it is another matter entirely.\n\nThe Perl subroutine, Inc, below takes 2 parameters and increments each directly.\n\nsub Inc\n{\n++ $[0];\n++ $[1];\n}\n\nand here is a C function to call it.\n\nstatic void\ncallInc(a, b)\nint a;\nint b;\n{\ndSP;\nint count;\nSV * sva;\nSV * svb;\n\nENTER;\nSAVETMPS;\n\nsva = sv2mortal(newSViv(a));\nsvb = sv2mortal(newSViv(b));\n\nPUSHMARK(SP);\nEXTEND(SP, 2);\nPUSHs(sva);\nPUSHs(svb);\nPUTBACK;\n\ncount = callpv(\"Inc\", GDISCARD);\n\nif (count != 0)\ncroak (\"callInc: expected 0 values from 'Inc', got %d\\n\",\ncount);\n\nprintf (\"%d + 1 = %d\\n\", a, SvIV(sva));\nprintf (\"%d + 1 = %d\\n\", b, SvIV(svb));\n\nFREETMPS;\nLEAVE;\n}\n\nTo be able to access the two parameters that were pushed onto the stack after they return\nfrom callpv it is necessary to make a note of their addresses--thus the two variables \"sva\"\nand \"svb\".\n\nThe reason this is necessary is that the area of the Perl stack which held them will very\nlikely have been overwritten by something else by the time control returns from callpv.\n\nUsing GEVAL\nNow an example using GEVAL. Below is a Perl subroutine which computes the difference of its\n2 parameters. If this would result in a negative result, the subroutine calls die.\n\nsub Subtract\n{\nmy ($a, $b) = @;\n\ndie \"death can be fatal\\n\" if $a < $b;\n\n$a - $b;\n}\n\nand some C to call it\n\nstatic void\ncallSubtract(a, b)\nint a;\nint b;\n{\ndSP;\nint count;\nSV *errtmp;\n\nENTER;\nSAVETMPS;\n\nPUSHMARK(SP);\nEXTEND(SP, 2);\nPUSHs(sv2mortal(newSViv(a)));\nPUSHs(sv2mortal(newSViv(b)));\nPUTBACK;\n\ncount = callpv(\"Subtract\", GEVAL|GSCALAR);\n\nSPAGAIN;\n\n/* Check the eval first */\nerrtmp = ERRSV;\nif (SvTRUE(errtmp))\n{\nprintf (\"Uh oh - %s\\n\", SvPVnolen(errtmp));\nPOPs;\n}\nelse\n{\nif (count != 1)\ncroak(\"callSubtract: wanted 1 value from 'Subtract', got %d\\n\",\ncount);\n\nprintf (\"%d - %d = %d\\n\", a, b, POPi);\n}\n\nPUTBACK;\nFREETMPS;\nLEAVE;\n}\n\nIf callSubtract is called thus\n\ncallSubtract(4, 5)\n\nthe following will be printed\n\nUh oh - death can be fatal\n\nNotes\n\n1.   We want to be able to catch the die so we have used the GEVAL flag.  Not specifying\nthis flag would mean that the program would terminate immediately at the die statement\nin the subroutine Subtract.\n\n2.   The code\n\nerrtmp = ERRSV;\nif (SvTRUE(errtmp))\n{\nprintf (\"Uh oh - %s\\n\", SvPVnolen(errtmp));\nPOPs;\n}\n\nis the direct equivalent of this bit of Perl\n\nprint \"Uh oh - $@\\n\" if $@;\n\n\"PLerrgv\" is a perl global of type \"GV *\" that points to the symbol table entry\ncontaining the error.  \"ERRSV\" therefore refers to the C equivalent of $@.  We use a\nlocal temporary, \"errtmp\", since \"ERRSV\" is a macro that calls a function, and\n\"SvTRUE(ERRSV)\" would end up calling that function multiple times.\n\n3.   Note that the stack is popped using \"POPs\" in the block where \"SvTRUE(errtmp)\" is true.\nThis is necessary because whenever a call* function invoked with GEVAL|GSCALAR\nreturns an error, the top of the stack holds the value undef. Because we want the\nprogram to continue after detecting this error, it is essential that the stack be tidied\nup by removing the undef.\n\nUsing GKEEPERR\nConsider this rather facetious example, where we have used an XS version of the callSubtract\nexample above inside a destructor:\n\npackage Foo;\nsub new { bless {}, $[0] }\nsub Subtract {\nmy($a,$b) = @;\ndie \"death can be fatal\" if $a < $b;\n$a - $b;\n}\nsub DESTROY { callSubtract(5, 4); }\nsub foo { die \"foo dies\"; }\n\npackage main;\n{\nmy $foo = Foo->new;\neval { $foo->foo };\n}\nprint \"Saw: $@\" if $@;             # should be, but isn't\n\nThis example will fail to recognize that an error occurred inside the \"eval {}\".  Here's why:\nthe callSubtract code got executed while perl was cleaning up temporaries when exiting the\nouter braced block, and because callSubtract is implemented with callpv using the GEVAL\nflag, it promptly reset $@.  This results in the failure of the outermost test for $@, and\nthereby the failure of the error trap.\n\nAppending the GKEEPERR flag, so that the callpv call in callSubtract reads:\n\ncount = callpv(\"Subtract\", GEVAL|GSCALAR|GKEEPERR);\n\nwill preserve the error and restore reliable error handling.\n\nUsing callsv\nIn all the previous examples I have 'hard-wired' the name of the Perl subroutine to be called\nfrom C.  Most of the time though, it is more convenient to be able to specify the name of the\nPerl subroutine from within the Perl script, and you'll want to use callsv.\n\nConsider the Perl code below\n\nsub fred\n{\nprint \"Hello there\\n\";\n}\n\nCallSubPV(\"fred\");\n\nHere is a snippet of XSUB which defines CallSubPV.\n\nvoid\nCallSubPV(name)\nchar *  name\nCODE:\nPUSHMARK(SP);\ncallpv(name, GDISCARD|GNOARGS);\n\nThat is fine as far as it goes. The thing is, the Perl subroutine can be specified as only a\nstring, however, Perl allows references to subroutines and anonymous subroutines.  This is\nwhere callsv is useful.\n\nThe code below for CallSubSV is identical to CallSubPV except that the \"name\" parameter is\nnow defined as an SV* and we use callsv instead of callpv.\n\nvoid\nCallSubSV(name)\nSV *    name\nCODE:\nPUSHMARK(SP);\ncallsv(name, GDISCARD|GNOARGS);\n\nBecause we are using an SV to call fred the following can all be used:\n\nCallSubSV(\"fred\");\nCallSubSV(\\&fred);\n$ref = \\&fred;\nCallSubSV($ref);\nCallSubSV( sub { print \"Hello there\\n\" } );\n\nAs you can see, callsv gives you much greater flexibility in how you can specify the Perl\nsubroutine.\n\nYou should note that, if it is necessary to store the SV (\"name\" in the example above) which\ncorresponds to the Perl subroutine so that it can be used later in the program, it not enough\njust to store a copy of the pointer to the SV. Say the code above had been like this:\n\nstatic SV * rememberSub;\n\nvoid\nSaveSub1(name)\nSV *    name\nCODE:\nrememberSub = name;\n\nvoid\nCallSavedSub1()\nCODE:\nPUSHMARK(SP);\ncallsv(rememberSub, GDISCARD|GNOARGS);\n\nThe reason this is wrong is that, by the time you come to use the pointer \"rememberSub\" in\n\"CallSavedSub1\", it may or may not still refer to the Perl subroutine that was recorded in\n\"SaveSub1\".  This is particularly true for these cases:\n\nSaveSub1(\\&fred);\nCallSavedSub1();\n\nSaveSub1( sub { print \"Hello there\\n\" } );\nCallSavedSub1();\n\nBy the time each of the \"SaveSub1\" statements above has been executed, the SV*s which\ncorresponded to the parameters will no longer exist.  Expect an error message from Perl of\nthe form\n\nCan't use an undefined value as a subroutine reference at ...\n\nfor each of the \"CallSavedSub1\" lines.\n\nSimilarly, with this code\n\n$ref = \\&fred;\nSaveSub1($ref);\n$ref = 47;\nCallSavedSub1();\n\nyou can expect one of these messages (which you actually get is dependent on the version of\nPerl you are using)\n\nNot a CODE reference at ...\nUndefined subroutine &main::47 called ...\n\nThe variable $ref may have referred to the subroutine \"fred\" whenever the call to \"SaveSub1\"\nwas made but by the time \"CallSavedSub1\" gets called it now holds the number 47. Because we\nsaved only a pointer to the original SV in \"SaveSub1\", any changes to $ref will be tracked by\nthe pointer \"rememberSub\". This means that whenever \"CallSavedSub1\" gets called, it will\nattempt to execute the code which is referenced by the SV* \"rememberSub\".  In this case\nthough, it now refers to the integer 47, so expect Perl to complain loudly.\n\nA similar but more subtle problem is illustrated with this code:\n\n$ref = \\&fred;\nSaveSub1($ref);\n$ref = \\&joe;\nCallSavedSub1();\n\nThis time whenever \"CallSavedSub1\" gets called it will execute the Perl subroutine \"joe\"\n(assuming it exists) rather than \"fred\" as was originally requested in the call to\n\"SaveSub1\".\n\nTo get around these problems it is necessary to take a full copy of the SV.  The code below\nshows \"SaveSub2\" modified to do that.\n\n/* this isn't thread-safe */\nstatic SV * keepSub = (SV*)NULL;\n\nvoid\nSaveSub2(name)\nSV *    name\nCODE:\n/* Take a copy of the callback */\nif (keepSub == (SV*)NULL)\n/* First time, so create a new SV */\nkeepSub = newSVsv(name);\nelse\n/* Been here before, so overwrite */\nSvSetSV(keepSub, name);\n\nvoid\nCallSavedSub2()\nCODE:\nPUSHMARK(SP);\ncallsv(keepSub, GDISCARD|GNOARGS);\n\nTo avoid creating a new SV every time \"SaveSub2\" is called, the function first checks to see\nif it has been called before.  If not, then space for a new SV is allocated and the reference\nto the Perl subroutine \"name\" is copied to the variable \"keepSub\" in one operation using\n\"newSVsv\".  Thereafter, whenever \"SaveSub2\" is called, the existing SV, \"keepSub\", is\noverwritten with the new value using \"SvSetSV\".\n\nNote: using a static or global variable to store the SV isn't thread-safe.  You can either\nuse the \"MYCXT\" mechanism documented in \"Safely Storing Static Data in XS\" in perlxs which\nis fast, or store the values in perl global variables, using getsv(), which is much slower.\n\nUsing callargv\nHere is a Perl subroutine which prints whatever parameters are passed to it.\n\nsub PrintList\n{\nmy(@list) = @;\n\nforeach (@list) { print \"$\\n\" }\n}\n\nAnd here is an example of callargv which will call PrintList.\n\nstatic char * words[] = {\"alpha\", \"beta\", \"gamma\", \"delta\", NULL};\n\nstatic void\ncallPrintList()\n{\ncallargv(\"PrintList\", GDISCARD, words);\n}\n\nNote that it is not necessary to call \"PUSHMARK\" in this instance.  This is because callargv\nwill do it for you.\n\nUsing callmethod\nConsider the following Perl code:\n\n{\npackage Mine;\n\nsub new\n{\nmy($type) = shift;\nbless [@]\n}\n\nsub Display\n{\nmy ($self, $index) = @;\nprint \"$index: $$self[$index]\\n\";\n}\n\nsub PrintID\n{\nmy($class) = @;\nprint \"This is Class $class version 1.0\\n\";\n}\n}\n\nIt implements just a very simple class to manage an array.  Apart from the constructor,\n\"new\", it declares methods, one static and one virtual. The static method, \"PrintID\", prints\nout simply the class name and a version number. The virtual method, \"Display\", prints out a\nsingle element of the array.  Here is an all-Perl example of using it.\n\n$a = Mine->new('red', 'green', 'blue');\n$a->Display(1);\nMine->PrintID;\n\nwill print\n\n1: green\nThis is Class Mine version 1.0\n\nCalling a Perl method from C is fairly straightforward. The following things are required:\n\n•    A reference to the object for a virtual method or the name of the class for a static\nmethod\n\n•    The name of the method\n\n•    Any other parameters specific to the method\n\nHere is a simple XSUB which illustrates the mechanics of calling both the \"PrintID\" and\n\"Display\" methods from C.\n\nvoid\ncallMethod(ref, method, index)\nSV *    ref\nchar *  method\nint             index\nCODE:\nPUSHMARK(SP);\nEXTEND(SP, 2);\nPUSHs(ref);\nPUSHs(sv2mortal(newSViv(index)));\nPUTBACK;\n\ncallmethod(method, GDISCARD);\n\nvoid\ncallPrintID(class, method)\nchar *  class\nchar *  method\nCODE:\nPUSHMARK(SP);\nXPUSHs(sv2mortal(newSVpv(class, 0)));\nPUTBACK;\n\ncallmethod(method, GDISCARD);\n\nSo the methods \"PrintID\" and \"Display\" can be invoked like this:\n\n$a = Mine->new('red', 'green', 'blue');\ncallMethod($a, 'Display', 1);\ncallPrintID('Mine', 'PrintID');\n\nThe only thing to note is that, in both the static and virtual methods, the method name is\nnot passed via the stack--it is used as the first parameter to callmethod.\n\nUsing GIMMEV\nHere is a trivial XSUB which prints the context in which it is currently executing.\n\nvoid\nPrintContext()\nCODE:\nU8 gimme = GIMMEV;\nif (gimme == GVOID)\nprintf (\"Context is Void\\n\");\nelse if (gimme == GSCALAR)\nprintf (\"Context is Scalar\\n\");\nelse\nprintf (\"Context is Array\\n\");\n\nAnd here is some Perl to test it.\n\nPrintContext;\n$a = PrintContext;\n@a = PrintContext;\n\nThe output from that will be\n\nContext is Void\nContext is Scalar\nContext is Array\n"
                    },
                    {
                        "name": "Using Perl to Dispose of Temporaries",
                        "content": "In the examples given to date, any temporaries created in the callback (i.e., parameters\npassed on the stack to the call* function or values returned via the stack) have been freed\nby one of these methods:\n\n•    Specifying the GDISCARD flag with call*\n\n•    Explicitly using the \"ENTER\"/\"SAVETMPS\"--\"FREETMPS\"/\"LEAVE\" pairing\n\nThere is another method which can be used, namely letting Perl do it for you automatically\nwhenever it regains control after the callback has terminated.  This is done by simply not\nusing the\n\nENTER;\nSAVETMPS;\n...\nFREETMPS;\nLEAVE;\n\nsequence in the callback (and not, of course, specifying the GDISCARD flag).\n\nIf you are going to use this method you have to be aware of a possible memory leak which can\narise under very specific circumstances.  To explain these circumstances you need to know a\nbit about the flow of control between Perl and the callback routine.\n\nThe examples given at the start of the document (an error handler and an event driven\nprogram) are typical of the two main sorts of flow control that you are likely to encounter\nwith callbacks.  There is a very important distinction between them, so pay attention.\n\nIn the first example, an error handler, the flow of control could be as follows.  You have\ncreated an interface to an external library.  Control can reach the external library like\nthis\n\nperl --> XSUB --> external library\n\nWhilst control is in the library, an error condition occurs. You have previously set up a\nPerl callback to handle this situation, so it will get executed. Once the callback has\nfinished, control will drop back to Perl again.  Here is what the flow of control will be\nlike in that situation\n\nperl --> XSUB --> external library\n...\nerror occurs\n...\nexternal library --> call* --> perl\n|\nperl <-- XSUB <-- external library <-- call* <----+\n\nAfter processing of the error using call* is completed, control reverts back to Perl more or\nless immediately.\n\nIn the diagram, the further right you go the more deeply nested the scope is.  It is only\nwhen control is back with perl on the extreme left of the diagram that you will have dropped\nback to the enclosing scope and any temporaries you have left hanging around will be freed.\n\nIn the second example, an event driven program, the flow of control will be more like this\n\nperl --> XSUB --> event handler\n...\nevent handler --> call* --> perl\n|\nevent handler <-- call* <----+\n...\nevent handler --> call* --> perl\n|\nevent handler <-- call* <----+\n...\nevent handler --> call* --> perl\n|\nevent handler <-- call* <----+\n\nIn this case the flow of control can consist of only the repeated sequence\n\nevent handler --> call* --> perl\n\nfor practically the complete duration of the program.  This means that control may never drop\nback to the surrounding scope in Perl at the extreme left.\n\nSo what is the big problem? Well, if you are expecting Perl to tidy up those temporaries for\nyou, you might be in for a long wait.  For Perl to dispose of your temporaries, control must\ndrop back to the enclosing scope at some stage.  In the event driven scenario that may never\nhappen.  This means that, as time goes on, your program will create more and more\ntemporaries, none of which will ever be freed. As each of these temporaries consumes some\nmemory your program will eventually consume all the available memory in your system--kapow!\n\nSo here is the bottom line--if you are sure that control will revert back to the enclosing\nPerl scope fairly quickly after the end of your callback, then it isn't absolutely necessary\nto dispose explicitly of any temporaries you may have created. Mind you, if you are at all\nuncertain about what to do, it doesn't do any harm to tidy up anyway.\n"
                    },
                    {
                        "name": "Strategies for Storing Callback Context Information",
                        "content": "Potentially one of the trickiest problems to overcome when designing a callback interface can\nbe figuring out how to store the mapping between the C callback function and the Perl\nequivalent.\n\nTo help understand why this can be a real problem first consider how a callback is set up in\nan all C environment.  Typically a C API will provide a function to register a callback.\nThis will expect a pointer to a function as one of its parameters.  Below is a call to a\nhypothetical function \"registerfatal\" which registers the C function to get called when a\nfatal error occurs.\n\nregisterfatal(cb1);\n\nThe single parameter \"cb1\" is a pointer to a function, so you must have defined \"cb1\" in your\ncode, say something like this\n\nstatic void\ncb1()\n{\nprintf (\"Fatal Error\\n\");\nexit(1);\n}\n\nNow change that to call a Perl subroutine instead\n\nstatic SV * callback = (SV*)NULL;\n\nstatic void\ncb1()\n{\ndSP;\n\nPUSHMARK(SP);\n\n/* Call the Perl sub to process the callback */\ncallsv(callback, GDISCARD);\n}\n\n\nvoid\nregisterfatal(fn)\nSV *    fn\nCODE:\n/* Remember the Perl sub */\nif (callback == (SV*)NULL)\ncallback = newSVsv(fn);\nelse\nSvSetSV(callback, fn);\n\n/* register the callback with the external library */\nregisterfatal(cb1);\n\nwhere the Perl equivalent of \"registerfatal\" and the callback it registers, \"pcb1\", might\nlook like this\n\n# Register the sub pcb1\nregisterfatal(\\&pcb1);\n\nsub pcb1\n{\ndie \"I'm dying...\\n\";\n}\n\nThe mapping between the C callback and the Perl equivalent is stored in the global variable\n\"callback\".\n\nThis will be adequate if you ever need to have only one callback registered at any time. An\nexample could be an error handler like the code sketched out above. Remember though, repeated\ncalls to \"registerfatal\" will replace the previously registered callback function with the\nnew one.\n\nSay for example you want to interface to a library which allows asynchronous file i/o.  In\nthis case you may be able to register a callback whenever a read operation has completed. To\nbe of any use we want to be able to call separate Perl subroutines for each file that is\nopened.  As it stands, the error handler example above would not be adequate as it allows\nonly a single callback to be defined at any time. What we require is a means of storing the\nmapping between the opened file and the Perl subroutine we want to be called for that file.\n\nSay the i/o library has a function \"asynchread\" which associates a C function \"ProcessRead\"\nwith a file handle \"fh\"--this assumes that it has also provided some routine to open the file\nand so obtain the file handle.\n\nasynchread(fh, ProcessRead)\n\nThis may expect the C ProcessRead function of this form\n\nvoid\nProcessRead(fh, buffer)\nint fh;\nchar *      buffer;\n{\n...\n}\n\nTo provide a Perl interface to this library we need to be able to map between the \"fh\"\nparameter and the Perl subroutine we want called.  A hash is a convenient mechanism for\nstoring this mapping.  The code below shows a possible implementation\n\nstatic HV * Mapping = (HV*)NULL;\n\nvoid\nasynchread(fh, callback)\nint     fh\nSV *    callback\nCODE:\n/* If the hash doesn't already exist, create it */\nif (Mapping == (HV*)NULL)\nMapping = newHV();\n\n/* Save the fh -> callback mapping */\nhvstore(Mapping, (char*)&fh, sizeof(fh), newSVsv(callback), 0);\n\n/* Register with the C Library */\nasynchread(fh, asynchreadif);\n\nand \"asynchreadif\" could look like this\n\nstatic void\nasynchreadif(fh, buffer)\nint fh;\nchar *      buffer;\n{\ndSP;\nSV  sv;\n\n/* Get the callback associated with fh */\nsv =  hvfetch(Mapping, (char*)&fh , sizeof(fh), FALSE);\nif (sv == (SV)NULL)\ncroak(\"Internal error...\\n\");\n\nPUSHMARK(SP);\nEXTEND(SP, 2);\nPUSHs(sv2mortal(newSViv(fh)));\nPUSHs(sv2mortal(newSVpv(buffer, 0)));\nPUTBACK;\n\n/* Call the Perl sub */\ncallsv(*sv, GDISCARD);\n}\n\nFor completeness, here is \"asynchclose\".  This shows how to remove the entry from the hash\n\"Mapping\".\n\nvoid\nasynchclose(fh)\nint     fh\nCODE:\n/* Remove the entry from the hash */\n(void) hvdelete(Mapping, (char*)&fh, sizeof(fh), GDISCARD);\n\n/* Now call the real asynchclose */\nasynchclose(fh);\n\nSo the Perl interface would look like this\n\nsub callback1\n{\nmy($handle, $buffer) = @;\n}\n\n# Register the Perl callback\nasynchread($fh, \\&callback1);\n\nasynchclose($fh);\n\nThe mapping between the C callback and Perl is stored in the global hash \"Mapping\" this time.\nUsing a hash has the distinct advantage that it allows an unlimited number of callbacks to be\nregistered.\n\nWhat if the interface provided by the C callback doesn't contain a parameter which allows the\nfile handle to Perl subroutine mapping?  Say in the asynchronous i/o package, the callback\nfunction gets passed only the \"buffer\" parameter like this\n\nvoid\nProcessRead(buffer)\nchar *      buffer;\n{\n...\n}\n\nWithout the file handle there is no straightforward way to map from the C callback to the\nPerl subroutine.\n\nIn this case a possible way around this problem is to predefine a series of C functions to\nact as the interface to Perl, thus\n\n#define MAXCB              3\n#define NULLHANDLE -1\ntypedef void (*FnMap)();\n\nstruct MapStruct {\nFnMap    Function;\nSV *     PerlSub;\nint      Handle;\n};\n\nstatic void  fn1();\nstatic void  fn2();\nstatic void  fn3();\n\nstatic struct MapStruct Map [MAXCB] =\n{\n{ fn1, NULL, NULLHANDLE },\n{ fn2, NULL, NULLHANDLE },\n{ fn3, NULL, NULLHANDLE }\n};\n\nstatic void\nPcb(index, buffer)\nint index;\nchar * buffer;\n{\ndSP;\n\nPUSHMARK(SP);\nXPUSHs(sv2mortal(newSVpv(buffer, 0)));\nPUTBACK;\n\n/* Call the Perl sub */\ncallsv(Map[index].PerlSub, GDISCARD);\n}\n\nstatic void\nfn1(buffer)\nchar * buffer;\n{\nPcb(0, buffer);\n}\n\nstatic void\nfn2(buffer)\nchar * buffer;\n{\nPcb(1, buffer);\n}\n\nstatic void\nfn3(buffer)\nchar * buffer;\n{\nPcb(2, buffer);\n}\n\nvoid\narrayasynchread(fh, callback)\nint             fh\nSV *    callback\nCODE:\nint index;\nint nullindex = MAXCB;\n\n/* Find the same handle or an empty entry */\nfor (index = 0; index < MAXCB; ++index)\n{\nif (Map[index].Handle == fh)\nbreak;\n\nif (Map[index].Handle == NULLHANDLE)\nnullindex = index;\n}\n\nif (index == MAXCB && nullindex == MAXCB)\ncroak (\"Too many callback functions registered\\n\");\n\nif (index == MAXCB)\nindex = nullindex;\n\n/* Save the file handle */\nMap[index].Handle = fh;\n\n/* Remember the Perl sub */\nif (Map[index].PerlSub == (SV*)NULL)\nMap[index].PerlSub = newSVsv(callback);\nelse\nSvSetSV(Map[index].PerlSub, callback);\n\nasynchread(fh, Map[index].Function);\n\nvoid\narrayasynchclose(fh)\nint     fh\nCODE:\nint index;\n\n/* Find the file handle */\nfor (index = 0; index < MAXCB; ++ index)\nif (Map[index].Handle == fh)\nbreak;\n\nif (index == MAXCB)\ncroak (\"could not close fh %d\\n\", fh);\n\nMap[index].Handle = NULLHANDLE;\nSvREFCNTdec(Map[index].PerlSub);\nMap[index].PerlSub = (SV*)NULL;\n\nasynchclose(fh);\n\nIn this case the functions \"fn1\", \"fn2\", and \"fn3\" are used to remember the Perl subroutine\nto be called. Each of the functions holds a separate hard-wired index which is used in the\nfunction \"Pcb\" to access the \"Map\" array and actually call the Perl subroutine.\n\nThere are some obvious disadvantages with this technique.\n\nFirstly, the code is considerably more complex than with the previous example.\n\nSecondly, there is a hard-wired limit (in this case 3) to the number of callbacks that can\nexist simultaneously. The only way to increase the limit is by modifying the code to add more\nfunctions and then recompiling.  None the less, as long as the number of functions is chosen\nwith some care, it is still a workable solution and in some cases is the only one available.\n\nTo summarize, here are a number of possible methods for you to consider for storing the\nmapping between C and the Perl callback\n\n1. Ignore the problem - Allow only 1 callback\nFor a lot of situations, like interfacing to an error handler, this may be a perfectly\nadequate solution.\n\n2. Create a sequence of callbacks - hard wired limit\nIf it is impossible to tell from the parameters passed back from the C callback what the\ncontext is, then you may need to create a sequence of C callback interface functions,\nand store pointers to each in an array.\n\n3. Use a parameter to map to the Perl callback\nA hash is an ideal mechanism to store the mapping between C and Perl.\n"
                    },
                    {
                        "name": "Alternate Stack Manipulation",
                        "content": "Although I have made use of only the \"POP*\" macros to access values returned from Perl\nsubroutines, it is also possible to bypass these macros and read the stack using the \"ST\"\nmacro (See perlxs for a full description of the \"ST\" macro).\n\nMost of the time the \"POP*\" macros should be adequate; the main problem with them is that\nthey force you to process the returned values in sequence. This may not be the most suitable\nway to process the values in some cases. What we want is to be able to access the stack in a\nrandom order. The \"ST\" macro as used when coding an XSUB is ideal for this purpose.\n\nThe code below is the example given in the section \"Returning a List of Values\" recoded to\nuse \"ST\" instead of \"POP*\".\n\nstatic void\ncallAddSubtract2(a, b)\nint a;\nint b;\n{\ndSP;\nI32 ax;\nint count;\n\nENTER;\nSAVETMPS;\n\nPUSHMARK(SP);\nEXTEND(SP, 2);\nPUSHs(sv2mortal(newSViv(a)));\nPUSHs(sv2mortal(newSViv(b)));\nPUTBACK;\n\ncount = callpv(\"AddSubtract\", GARRAY);\n\nSPAGAIN;\nSP -= count;\nax = (SP - PLstackbase) + 1;\n\nif (count != 2)\ncroak(\"Big trouble\\n\");\n\nprintf (\"%d + %d = %d\\n\", a, b, SvIV(ST(0)));\nprintf (\"%d - %d = %d\\n\", a, b, SvIV(ST(1)));\n\nPUTBACK;\nFREETMPS;\nLEAVE;\n}\n\nNotes\n\n1.   Notice that it was necessary to define the variable \"ax\".  This is because the \"ST\"\nmacro expects it to exist.  If we were in an XSUB it would not be necessary to define\n\"ax\" as it is already defined for us.\n\n2.   The code\n\nSPAGAIN;\nSP -= count;\nax = (SP - PLstackbase) + 1;\n\nsets the stack up so that we can use the \"ST\" macro.\n\n3.   Unlike the original coding of this example, the returned values are not accessed in\nreverse order.  So ST(0) refers to the first value returned by the Perl subroutine and\n\"ST(count-1)\" refers to the last.\n"
                    },
                    {
                        "name": "Creating and Calling an Anonymous Subroutine in C",
                        "content": "As we've already shown, \"callsv\" can be used to invoke an anonymous subroutine.  However,\nour example showed a Perl script invoking an XSUB to perform this operation.  Let's see how\nit can be done inside our C code:\n\n...\n\nSV *cvrv\n= evalpv(\"sub {\nprint 'You will not find me cluttering any namespace!'\n}\", TRUE);\n\n...\n\ncallsv(cvrv, GVOID|GNOARGS);\n\n\"evalpv\" is used to compile the anonymous subroutine, which will be the return value as well\n(read more about \"evalpv\" in \"evalpv\" in perlapi).  Once this code reference is in hand, it\ncan be mixed in with all the previous examples we've shown.\n"
                    }
                ]
            },
            "LIGHTWEIGHT CALLBACKS": {
                "content": "Sometimes you need to invoke the same subroutine repeatedly.  This usually happens with a\nfunction that acts on a list of values, such as Perl's built-in sort(). You can pass a\ncomparison function to sort(), which will then be invoked for every pair of values that needs\nto be compared. The first() and reduce() functions from List::Util follow a similar pattern.\n\nIn this case it is possible to speed up the routine (often quite substantially) by using the\nlightweight callback API.  The idea is that the calling context only needs to be created and\ndestroyed once, and the sub can be called arbitrarily many times in between.\n\nIt is usual to pass parameters using global variables (typically $ for one parameter, or $a\nand $b for two parameters) rather than via @. (It is possible to use the @ mechanism if you\nknow what you're doing, though there is as yet no supported API for it. It's also inherently\nslower.)\n\nThe pattern of macro calls is like this:\n\ndMULTICALL;                 /* Declare local variables */\nU8 gimme = GSCALAR;        /* context of the call: GSCALAR,\n* GARRAY, or GVOID */\n\nPUSHMULTICALL(cv);         /* Set up the context for calling cv,\nand set local vars appropriately */\n\n/* loop */ {\n/* set the value(s) af your parameter variables */\nMULTICALL;              /* Make the actual call */\n} /* end of loop */\n\nPOPMULTICALL;              /* Tear down the calling context */\n\nFor some concrete examples, see the implementation of the first() and reduce() functions of\nList::Util 1.18. There you will also find a header file that emulates the multicall API on\nolder versions of perl.\n",
                "subsections": []
            },
            "SEE ALSO": {
                "content": "perlxs, perlguts, perlembed\n",
                "subsections": []
            },
            "AUTHOR": {
                "content": "Paul Marquess\n\nSpecial thanks to the following people who assisted in the creation of the document.\n\nJeff Okamoto, Tim Bunce, Nick Gianniotis, Steve Kelem, Gurusamy Sarathy and Larry Wall.\n",
                "subsections": []
            },
            "DATE": {
                "content": "Last updated for perl 5.23.1.\n\n\n\nperl v5.34.0                                 2026-06-23                                  PERLCALL(1)",
                "subsections": []
            }
        }
    }
}