home *** CD-ROM | disk | FTP | other *** search
/ ftp.cse.unsw.edu.au / 2014.06.ftp.cse.unsw.edu.au.tar / ftp.cse.unsw.edu.au / pub / doc / languages / perl / Connecting C Functions To Perl next >
Encoding:
Text File  |  1992-10-18  |  19.5 KB  |  616 lines

  1. Path: usage.csd.unsw.oz.au!metro!munnari.oz.au!spool.mu.edu!olivea!apple!veritas!amdcad!sono!waldman
  2. From: waldman@sono.uucp (Waldman Micah)
  3. Newsgroups: comp.lang.perl
  4. Subject: Connecting C functions to Perl
  5. Message-ID: <1991Jul17.042046.16096@sono.uucp>
  6. Date: 17 Jul 91 04:20:46 GMT
  7. Distribution: comp
  8. Organization: Acuson; Mountain View, California
  9. Lines: 604
  10.  
  11.  
  12.  
  13. Recently I had to connect a package of C functions to Perl. After doing so I
  14. wrote a document describing the procedure in detail (somewhat more than the
  15. README file in the usub directory ...) for maintenance purposes. I'm
  16. posting it here in the hope that it will make connecting C to Perl easier, so
  17. that more people will do it, so that more people will use Perl.
  18.  
  19. One request though: I would very much appreciate it if someone (Larry?
  20. Randal? Tom?) will go over it to make sure that the descriptions are correct
  21. and that the stated reasons for things being as they are match reality and 
  22. the intentions of the designers (str_2mortal would be a good case). 
  23.  
  24. I'm relocating at the end of the week and won't have access to the group for
  25. about 3 months (they don't have workstations in the Rockies). If someone
  26. wants to pick up the responsibility for correcting and updating the
  27. document, that would be great. Also it probably should be added to a FAQ
  28. which should be created (unless it exists and I don't know about it).
  29.  
  30. Enough talk. Enjoy connecting C to Perl.
  31.  
  32.                             Micah (Michael is fine) Waldman
  33.                             Now in California, soon back in Israel.
  34.  
  35.  
  36.  
  37.                 Connecting C Functions to Perl
  38.                 ==============================
  39.  
  40.  
  41. Introduction
  42. ------------
  43.  
  44. This document describes how to connect C functions to Perl. It contains the
  45. following sections:
  46.  
  47.     - Overview.
  48.         Lists the major steps in connecting C functions to Perl.
  49.  
  50.     - Initialization Function.
  51.         How to register functions and variables with Perl.
  52.  
  53.     - Subroutines Interface Function.
  54.         The interface between the Perl subroutines and the C functions.
  55.  
  56.     - Passing Arguments.
  57.         The mechanisms for passing arguments and the tools for analyzing them.
  58.  
  59.     - Variables Interface Functions.
  60.         Sharing variables between the Perl program and the C functions.
  61.  
  62.     - Compiling and Linking.
  63.         Putting it all together.
  64.  
  65. You should also look at the README file in the usub directory of Perl's
  66. source and at the examples provided there.
  67.  
  68. Warning: This document is written based on my experience and on browsing
  69. over Perl's source. It should be treated as containing guidelines and not as
  70. the official documentation.
  71.  
  72.  
  73. Overview
  74. --------
  75.  
  76. In the process of building Perl a file named uperl.o is created. This object
  77. file is then linked with your C code to create your own version of Perl.
  78. The items which are added to uperl.o are:
  79.  
  80.     - An initialization function which registers with Perl all the C
  81.       functions which will be called from a Perl program and all the
  82.       variables which will be shared by the C functions and the Perl
  83.       program.
  84.  
  85.     - For each C function that will be called from Perl there is an
  86.       "interface" which translates arguments from the Perl representation to
  87.       the C representation, calls the C function and then performs the
  88.       translation in the opposite direction. Each C function interface can be
  89.       in a separate function, or several interfaces may be grouped together.
  90.       In the latter case each interface (which corresponds to a specific 
  91.       C function) within a group is identified by a number (an index) which
  92.       was specified when the function was registered in the initialization
  93.       function.
  94.  
  95.     - The C functions themselves and any libraries they need.
  96.  
  97.     - For each variable which will be shared between the Perl program and
  98.       the C functions there is an interface which translates between C and
  99.       Perl representations. The interface is divided into two parts: C to
  100.       Perl, and Perl to C. Again, each interface can reside alone (in a pair
  101.       of separate functions) or several interfaces can be grouped together
  102.       into two functions that identify the variable within the group by an
  103.       index.
  104.  
  105.  
  106. Initialization Function
  107. -----------------------
  108.  
  109.     The Perl source file usersub.c contains a function called userinit.
  110.     You should add to it a call to your initialization function. (You can
  111.     actually do all of your initialization inside userinit but if there are
  112.     several C packages linked to Perl it is probably best for each to call
  113.     its separate initialization function.) Your initialization function
  114.     description follows.
  115.  
  116.     Arguments:
  117.         None.
  118.  
  119.     Returns:
  120.         Nothing.
  121.  
  122.     Structure:
  123.         DECLARE SUBROUTINE.
  124.             (Specify its name in Perl, its index number, the C function which
  125.             contains its interface, and the file name in which it resides.)
  126.         DECLARE SUBROUTINE.
  127.         DECLARE SUBROUTINE.
  128.         ... (As many as needed)
  129.  
  130.         DECLARE VARIABLE.
  131.             (Specify its name in Perl, its index number, the "set" function
  132.             which handles the Perl-TO-C translation, and the "get" function
  133.             which handles the C-TO-Perl translation.)
  134.         DECLARE VARIABLE.
  135.         DECLARE VARIABLE.
  136.         ... (As many as needed)
  137.  
  138.     Description:
  139.         - DECLARE SUBROUTINE:
  140.           To declare a subroutine you call make_usub which is declared as:
  141.  
  142.           SUBR *
  143.           make_usub(name, ix, subaddr, filename)
  144.           char *name;
  145.           int ix;
  146.           int (*subaddr)();
  147.           char *filename;
  148.  
  149.           The function's return value is not used.
  150.           name        - The name of the subroutine as used in a Perl program.
  151.           ix        - The index number of the subroutine.
  152.           subaddr    - The address of the C function that handles the interfacing
  153.                       between Perl and C for the subroutine.
  154.           filename    - Name of file where the C function resides (or maybe where
  155.                       the interface resides - I'm not sure).
  156.  
  157.           The index values are usually generated using an enumerated
  158.           declaration:
  159.  
  160.           static enum usersubs
  161.           {
  162.                 US_first_func,
  163.                 US_second_func,
  164.                 US_many_more_funcs,
  165.           };
  166.  
  167.           Then a typical call to make_usub would be:
  168.  
  169.           make_usub("first_func",    US_first_func,    sub_handler, "thisfile");
  170.  
  171.           (Of course you may want to use more meaningful names ...)
  172.  
  173.         - DECLARE VARIABLE:
  174.           To declare a variable you call magicname which is declared as:
  175.  
  176.           void
  177.           magicname(sym,name,namelen)
  178.           char *sym;
  179.           char *name;
  180.           int namelen;
  181.  
  182.           sym        - The name of the variable as used in a Perl program.
  183.           name        - The address of a structure which holds the variables
  184.                       interface functions' addresses and its index number.
  185.                       The structure is declared as:
  186.  
  187.                       struct ufuncs
  188.                       {
  189.                           int (*uf_val)();
  190.                           int (*uf_set)();
  191.                           int uf_index;
  192.                       };
  193.  
  194.                       uf_val    - The address of the C function that handles
  195.                                   the C-TO-Perl translation.
  196.                       uf_set    - The address of the C function that handles
  197.                                   the Perl-TO-C translation.
  198.                       uf_index    - The index number of the variable.
  199.  
  200.                       This structure should be set each time before calling
  201.                       magicname. A macro can be used (check the examples
  202.                       that come with the source).
  203.           namelen    - The size of the ufuncs structure.
  204.  
  205.  
  206. Subroutines Interface Function
  207. ------------------------------
  208.  
  209.     This document will only describe grouping all the interfaces into one
  210.     functions. The other way of putting them each in a separate function
  211.     uses the same principles.
  212.  
  213.     Arguments:
  214.         The function is declared as follows:
  215.  
  216.         static int
  217.         sub_handler (sub_index, stack_ptr, n_args)
  218.         int                sub_index;
  219.         register int    stack_ptr;
  220.         register int    n_args;
  221.  
  222.         - sub_index
  223.                 Index number of the called subroutine (as specified in the
  224.                 initialization function when the subroutine was registered).
  225.         - stack_ptr
  226.                 Stack pointer for getting arguments passed to the called
  227.                 subroutine. Will be explained in the 'Passing Arguments'
  228.                 section below.
  229.         - n_args
  230.                 Number of arguments passed to called subroutine.
  231.  
  232.     Returns:
  233.         - Stack pointer for returning results from the called subroutine.
  234.           Will be explained in the 'Passing Arguments' section below.
  235.  
  236.     Structure:
  237.         INITIALIZATIONS.
  238.         SWITCH BY INDEX:
  239.             CASE INDEX 1:
  240.                 CHECK NUMBER OF ARGUMENTS PASSED TO CALLED SUBROUTINE.
  241.                 TRANSLATE ARGUMENTS FROM PERL TO C REPRESENTATION.
  242.                 CALL ACTUAL C FUNCTION.
  243.                 TRANSLATE RESULTS FROM C TO PERL REPRESENTATION.
  244.                 RETURN WITH STACK.
  245.             CASE INDEX 2:
  246.                 CHECK NUMBER OF ARGUMENTS PASSED TO CALLED SUBROUTINE.
  247.                 TRANSLATE ARGUMENTS FROM PERL TO C REPRESENTATION.
  248.                 CALL ACTUAL C FUNCTION.
  249.                 TRANSLATE RESULTS FROM C TO PERL REPRESENTATION.
  250.                 RETURN WITH STACK.
  251.             ... (As many as needed)
  252.             DEFAULT:
  253.                 ERROR - UNIMPLEMENTED SUBROUTINE.
  254.                 RETURN WITH STACK.
  255.  
  256.     Description:
  257.         - INITIALIZATIONS:
  258.           The following variables should be declared:
  259.  
  260.           STR **st = stack->ary_array + sp;
  261.           register STR *Str;
  262.  
  263.           The first (st) will be used to access the arguments on the stack
  264.           (which will be explained in the 'Passing Arguments' section below).
  265.           The second (Str) is used by some Perl macros (e.g. str_get,
  266.           str_gnum).
  267.  
  268.         - CHECK NUMBER OF ARGUMENTS PASSED TO CALLED SUBROUTINE.
  269.           Use n_args to verify that the correct number of arguments were
  270.           passed to the function. If not use the fatal() function to produce
  271.           a usage error message. for example:
  272.  
  273.           if ( n_args != 0 )
  274.                 fatal ("Usage: &call_me()");
  275.  
  276.         - TRANSLATE ARGUMENTS FROM PERL TO C REPRESENTATION.
  277.           Will be explained in the 'Passing Arguments' section below.
  278.  
  279.         - TRANSLATE RESULTS FROM C TO PERL REPRESENTATION.
  280.           Will be explained in the 'Passing Arguments' section below.
  281.  
  282.         - RETURN WITH STACK.
  283.           Return the stack pointer (which usually was not changed):
  284.  
  285.           return stack_ptr;
  286.  
  287.         - ERROR - UNIMPLEMENTED SUBROUTINE.
  288.           The only cause for executing the default case is if a subroutine
  289.           was registered with Perl by the initialization function but is not
  290.           implemented yet (i.e. no 'case' for it). Therefore we must issue
  291.           an error message:
  292.  
  293.           fatal("Unimplemented user-defined subroutine");
  294.  
  295.  
  296. Passing Arguments
  297. -----------------
  298.  
  299.     The stack:
  300.  
  301.         Perl passes arguments back and forth by placing them on the stack.
  302.         The stack (as everything else in Perl) is a STR which is a structure
  303.         that can hold anything - number, string, array, assoc. array, etc.
  304.         In the case of the stack the STR holds an array for the values of
  305.         the stack. Each item in this array (and so each item in the stack)
  306.         is also a STR. So, anything can be put on the stack - a number or a
  307.         string (I really don't know about putting an array in one item of
  308.         the stack. There is a way to return an array from a subroutine - see
  309.         later in this section). The only thing you need to remember is that
  310.         since STR is a Perl defined structure you cannot assign to it
  311.         directly (or rather, you don't want to). Instead, you use functions
  312.         supplied by Perl that do the necessary conversions from a number or
  313.         string to a STR. (The STR related definitions are in str.c and
  314.         str.h, the array related definitions are in array.c and array.h.)
  315.         The argument stack_ptr passed to the Subroutines Interface Function
  316.         is an index to the place on the stack where the called subroutine's
  317.         arguments begin. For convenience, we defined 'st' at the initialization
  318.         to point directly to that place and we'll use it from there on. 
  319.         The first item on the stack (st[0]) is the return value from the
  320.         subroutine. It should be set before returning. The following items
  321.         (st[1], st[2], ...) are the arguments of the subroutine. Each
  322.         argument may serve for input, output, or both.
  323.  
  324.     Getting arguments from the stack:
  325.  
  326.         The following functions can be used to get input arguments from the
  327.         stack:
  328.  
  329.         - str_get
  330.             Used to get a null terminated string, as in:
  331.  
  332.             char*    name    =    (char*)        str_get(st[1]);
  333.  
  334.             The first subroutine argument will be assigned as a string to
  335.             the pointer name.
  336.  
  337.         - str_2ptr
  338.             Used to get a non-null terminated string, as in:
  339.  
  340.             char*    buffer    =    (char*)        str_2ptr(st[1]);
  341.  
  342.             The first subroutine argument will be assigned as a non-null
  343.             terminated string to the pointer buffer.
  344.  
  345.         - str_gnum
  346.             Used to get a number, as in:
  347.  
  348.             int        num        =    (int)        str_gnum(st[2]);
  349.  
  350.             The second subroutine argument will be assigned as a number to
  351.             the variable num.
  352.  
  353.         - str_true
  354.             Used to get a boolean, as in:
  355.  
  356.             int        cleanup    =    (int)        str_true(st[3]);
  357.  
  358.             True or false will be assigned to the variable cleanup according
  359.             to the value of the third argument (see the Perl manual for a
  360.             definition of true and false values).
  361.  
  362.     Putting arguments on the stack:
  363.  
  364.         The following functions can be used to put output arguments on the
  365.         stack:
  366.  
  367.         - str_set
  368.             Used to set a null terminated string, as in:
  369.  
  370.             str_set(st[0], (char *) result);
  371.  
  372.             The value of the string pointed to by result will become the
  373.             return value of the subroutine (assuming it was called as a
  374.             function).
  375.  
  376.         - str_nset
  377.             Used to set a non-null terminated string, as in:
  378.  
  379.             str_nset (st[4], (char *) result, result_length);
  380.  
  381.             The value of the result_length bytes pointed to by result will
  382.             be assigned to the fourth argument of the subroutine.
  383.  
  384.         - str_numset
  385.             Used to set a number, as in:
  386.  
  387.             str_numset (st[0], (double) retval);
  388.  
  389.             The value of the integer retval will become the return value
  390.             of the subroutine (assuming it was called as a function). Notice
  391.             the casting to (double).
  392.  
  393.         The following values can be put on the stack:
  394.  
  395.         - str_undef
  396.             Used to return an undefined value, as in:
  397.  
  398.             st[0] = &str_undef;
  399.  
  400.             The return value of the subroutine will be undefined.
  401.  
  402.         - str_yes
  403.             Used to return a yes (true) value, as in:
  404.  
  405.             st[0] = &str_yes;
  406.  
  407.             The return value of the subroutine will be yes.
  408.  
  409.         - str_no
  410.             Used to return a no (false) value, as in:
  411.  
  412.             st[0] = &str_no;
  413.  
  414.             The return value of the subroutine will be no.
  415.  
  416.     Returning an array:
  417.  
  418.         Saying, above, that the first argument on the stack (st[0]) is the
  419.         return value of the subroutine is a simplification. If the
  420.         subroutine is called in a scalar context then st[0] will be its
  421.         return value. If, however, the subroutine is called in an array
  422.         context the return value is the list which begins in st[0] and ends
  423.         where the stack pointer returned from the sub_handler points to.
  424.         For example, if stack_ptr was 80 on entry, and is 85 on exit, A list
  425.         containing 6 elements (st[0] .. st[5]) will be returned from the
  426.         subroutine. If you want your subroutine to return different values
  427.         according to the context it was called from, you need to check the
  428.         context inside the sub_handler (explanation below) and put values
  429.         on the stack accordingly.
  430.         In case you want to return an array the first thing is to make sure
  431.         that the stack is large enough to hold the entire array. Use the
  432.         function astore() to do that. If 'array_size' is the size of the
  433.         array you want to put on the stack, call astore like this:
  434.  
  435.         astore (stack, stack_ptr + array_size, Nullstr);
  436.  
  437.         By doing that the stack may be reallocated in a new memory location.
  438.         Therefore, you must update st (the pointer directly to the arguments 
  439.         on the stack) like this:
  440.  
  441.         st = stack->ary_array + stack_ptr;
  442.  
  443.         Now you can put your array on the stack. Since you are creating new
  444.         STR's that will be on the stack (not just updating an output
  445.         argument) different functions should be used instead of str_set,
  446.         str_nset, and str_numset. The following are the equivalent
  447.         functions:
  448.  
  449.         - str_make
  450.             Used to create a STR from a string, as in:
  451.  
  452.             str_make (result, result_length);
  453.  
  454.             The value of the result_length bytes pointed to by result will
  455.             be assigned to a STR. A pointer will be returned to that STR.
  456.             If the length passed is 0 strlen() will be used to determine the
  457.             length of the string.
  458.  
  459.         - str_numset
  460.             Used to create a STR from a number, as in:
  461.  
  462.             str_nmake ((double) retval);
  463.  
  464.             The value of the integer retval will be assigned to a STR. A
  465.             pointer will be returned to that STR. Notice the casting to
  466.             (double).
  467.  
  468.         Since the array created on the stack is only temporary and not
  469.         needed after the whole expression was evaluated, the pointer
  470.         returned from str_make and str_nmake should be passed to
  471.         str_2mortal(), and its output should be assigned to the stack item.
  472.         The whole thing looks like this:
  473.  
  474.         for (item = 0 ; item < array_size; item++)
  475.         {
  476.             st[item] = str_2mortal (str_nmake ((double) array[item]));
  477.         }
  478.  
  479.         (Assuming an array of numbers is returned.)
  480.         As mentioned above the stack pointer returned should point to the
  481.         last array item. Therefore, continuing the example from above the
  482.         function should end with:
  483.  
  484.         return stack_ptr + array_size - 1;
  485.  
  486.     Checking the calling context:
  487.  
  488.         The context of the current subroutine being evaluated is held in
  489.         curcsv->wantarray. curcsv holds the current call-save information
  490.         (all kinds of information about the called subroutine). One of the
  491.         fields (wantarray) is a flag for the context:
  492.         - G_ARRAY : An array context.
  493.         - G_SCALAR: A scalar context.
  494.         curcsv is defined in perl.h so all you need to do is say:
  495.  
  496.         if ( curcsv-wantarray != G_ARRAY )
  497.         {
  498.             /* Scalar context */
  499.             str_numset (st[0], (double) array_size); /* or anything else */
  500.             return stack_ptr;
  501.         }
  502.         else
  503.         {
  504.             /* Array context */
  505.             astore (stack, stack_ptr + array_size, Nullstr);
  506.             st = stack->ary_array + stack_ptr;
  507.  
  508.             for (item = 0 ; item < array_size; item++)
  509.             {
  510.                 st[item] = str_2mortal (str_nmake ((double) array[item]));
  511.             }
  512.  
  513.             return stack_ptr + array_size - 1;
  514.         }
  515.  
  516.  
  517. Variables Interface Functions
  518. -----------------------------
  519.  
  520.     This document will only describe grouping all the interfaces into a pair
  521.     of functions. The other way of putting them each in a separate pair of 
  522.     functions uses the same principles. As explained above, there are tow
  523.     variables interface functions:
  524.     - var_set translates from Perl to C.
  525.     - var_get translates from C to Perl.
  526.  
  527.     Arguments:
  528.         Both functions are declared as follows:
  529.  
  530.         static int
  531.         var_get/var_set (var_index, str)
  532.         int        var_index;
  533.         STR        *str;
  534.  
  535.         - var_index
  536.                 Index number of the variable to be handled (as specified in
  537.                 the initialization function when the variable was registered).
  538.         - str
  539.                 A STR to which the value of the variable should be assigned
  540.                 (var_get) or from which the variable's value should be
  541.                 updated (var_set)..
  542.  
  543.     Returns:
  544.         - 0. I don't know what the meaning of it is.
  545.  
  546.     Structure:
  547.         INITIALIZATIONS.
  548.         SWITCH BY INDEX:
  549.             CASE INDEX 1:
  550.                 PUT VALUE OF VARIABLE IN STR.   or
  551.                 PUT VALUE OF STR IN VARIABLE.
  552.             CASE INDEX 2:
  553.                 PUT VALUE OF VARIABLE IN STR.   or
  554.                 PUT VALUE OF STR IN VARIABLE.
  555.             ... (As many as needed)
  556.             DEFAULT:
  557.                 ERROR - UNIMPLEMENTED VARIABLE.
  558.  
  559.     Description:
  560.         - INITIALIZATIONS:
  561.           The following variable should be declared in var_set:
  562.  
  563.           register STR *Str;
  564.  
  565.           It is used by some Perl macros (e.g. str_get, str_gnum).
  566.  
  567.         - PUT VALUE OF VARIABLE IN STR.
  568.           Use the functions described above to set a STR (str_set, str_nset,
  569.           str_numset).
  570.  
  571.         - PUT VALUE OF STR IN VARIABLE.
  572.           Use the functions described above to get a STR (str_get, str_gnum,
  573.           str_2ptr).
  574.  
  575.         - ERROR - UNIMPLEMENTED VARIABLE.
  576.           The only cause for executing the default case is if a variable
  577.           was registered with Perl by the initialization function but is not
  578.           implemented yet (i.e. no 'case' for it). Therefore we must issue
  579.           an error message:
  580.  
  581.           fatal("Unimplemented user-defined variable");
  582.  
  583.  
  584. Compiling and Linking
  585. ---------------------
  586.  
  587.     Assuming you already have uperl.o (from compiling Perl) a simple make
  588.     file might look like this:
  589.  
  590.     INC = /usr/src/perl            # or where you put your Perl source
  591.  
  592.     # assuming you want to connect the package 'pack' which has a library by
  593.     # that name.
  594.  
  595.     userperl: uperl.o usersub.o interface.o 
  596.         cc uperl.o usersub.o interface.o -lm -lpack -o userperl
  597.  
  598.     # the C sources include some Perl files so we need INC.
  599.  
  600.     usersub.o: usersub.c
  601.         cc -c -I$(INC) -g usersub.c
  602.  
  603.     interface.o: interface.c
  604.         cc -c -I$(INC) -g interface.c
  605.  
  606.  
  607.     After that, instead of calling perl you call userperl. As in:
  608.  
  609.     #! /usr/local/bin/userperl
  610.  
  611.     print "Just another Perl and C hacker\n";
  612.  
  613.  
  614.  
  615.                                     Micah Waldman
  616.