This is guile-ref.info, produced by Makeinfo version 3.12a from guile-ref.texi. INFO-DIR-SECTION Scheme Programming START-INFO-DIR-ENTRY * guile-ref: (guile-ref). The Guile Reference Manual. END-INFO-DIR-ENTRY Guile Reference Manual Copyright (C) 1996 Free Software Foundation Copyright (C) 1997 Free Software Foundation Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the Free Software Foundation.  File: guile-ref.info, Node: Networking Databases, Next: Network sockets, Up: Networking Networking Databases ==================== This section describes procedures which convert internet addresses and query various network databases. Care should be taken when using the database routines since they are not reentrant. -- primitive: inet-aton address Converts a string containing an Internet host address in the traditional dotted decimal notation into an integer. (inet-aton "127.0.0.1") => 2130706433 -- primitive: inet-ntoa number Converts an integer Internet host address into a string with the traditional dotted decimal representation. (inet-ntoa 2130706433) => "127.0.0.1" -- primitive: inet-netof address Returns the network number part of the given integer Internet address. (inet-netof 2130706433) => 127 -- primitive: inet-lnaof address Returns the local-address-with-network part of the given Internet address. (inet-lnaof 2130706433) => 1 -- primitive: inet-makeaddr net lna Makes an Internet host address by combining the network number NET with the local-address-within-network number LNA. (inet-makeaddr 127 1) => 2130706433 A "host object" is a structure that represents what is known about a network host, and is the usual way of representing a system's network identity inside software. The `hostent' functions accept a host object and return some information about that host's presence on the network. -- procedure: hostent:name host The "official" hostname for HOST. -- procedure: hostent:aliases host A list of aliases for HOST. -- procedure: hostent:addrtype host The host address type. For hosts with Internet addresses, this will return `AF_INET'. -- procedure: hostent:length host The length of each address for HOST, in bytes. -- procedure: hostent:addr-list host The list of network addresses associated with HOST. The `gethost' functions are used to find a particular host's entry in the host database. -- primitive: gethost [host] -- procedure: gethostbyname hostname -- procedure: gethostbyaddr address Look up a host by name or address, and return a host object. The `gethost' procedure will accept either a string name or an integer address; if given no arguments, it behaves like `gethostent' (see below). The following three procedures may be used to step through the host database from beginning to end. [FIXME: document the `sethost' variant of `sethostent'.] -- procedure: sethostent Initialize an internal stream from which host objects may be read. This procedure must be called before any calls to `gethostent', and may also be called afterward to reset the host entry stream. -- procedure: gethostent Return the next host object from the host database, or `#f' if there are no more hosts to be found (or an error has been encountered). This procedure may not be used before `sethostent' has been called. -- procedure: endhostent Close the stream used by `gethostent'. The return value is unspecified. The `netent' functions accept an object representing a network and return a selected component. -- procedure: netent:name net The "official" network name. -- procedure: netent:aliases net A list of aliases for the network. -- procedure: netent:addrtype net The type of the network number. Currently, this returns only `AF_INET'. -- procedure: netent:net net The network number. The `getnet' procedures look up a particular network in the network database. Each returns a "network object" that describes the network's technical nature. -- primitive: getnet [net] -- procedure: getnetbyname net-name -- procedure: getnetbyaddr net-number Look up a network by name or net number in the network database. The NET-NAME argument must be a string, and the NET-NUMBER argument must be an integer. `getnet' will accept either type of argument, behaving like `getnetent' (see below) if no arguments are given. [FIXME: document the `setnet' variant of `setnetent'.] -- procedure: setnetent Initializes a stream used by `getnetent' to read from the network database. The next use of `getnetent' will return the first entry. The return value is unspecified. -- procedure: getnetent Return the next entry from the network database. -- procedure: endnetent Close the stream used by `getnetent'. The return value is unspecified. The `protoent' procedures accept an object representing a protocol and return a selected component. -- procedure: protoent:name protocol The "official" protocol name. -- procedure: protoent:aliases protocol A list of aliases for the protocol. -- procedure: protoent:proto protocol The protocol number. The `getproto' procedures look up a particular network protocol and return a "protocol object". -- primitive: getproto [protocol] -- procedure: getprotobyname name -- procedure: getprotobynumber number Look up a network protocol by name or by number. `getprotobyname' takes a string argument, and `getprotobynumber' takes an integer argument. `getproto' will accept either type, behaving like `getprotoent' (see below) if no arguments are supplied. [FIXME: document the `setproto' variant of `setprotoent'.] -- procedure: setprotoent Initializes a stream used by `getprotoent' to read from the protocol database. The next use of `getprotoent' will return the first entry. The return value is unspecified. -- procedure: getprotoent Return the next entry from the protocol database. -- procedure: endprotoent Close the stream used by `getprotoent'. The return value is unspecified. The `servent' procedures accept a "service object" and return some information about that service. -- procedure: servent:name serv The "official" name of the network service. -- procedure: servent:aliases serv A list of aliases for the network service. -- procedure: servent:port serv The Internet port used by the service. -- procedure: servent:proto serv The protocol used by the service. A service may be listed many times in the database under different protocol names. The `getserv' procedures look up a network service and return a "service object" which describes the names and network ports conventionally assigned to the service. -- primitive: getserv [name protocol] -- procedure: getservbyname name protocol -- procedure: getservbyport port protocol Look up a network service by name or by service number, and return a network service object. The PROTOCOL argument specifies the name of the desired protocol; if the protocol found in the network service database does not match this name, a system error is signalled. The `getserv' procedure will take either a service name or number as its first argument; if given no arguments, it behaves like `getservent' (see below). [FIXME: document the `setserv' variant of `setservent'.] -- procedure: setservent Initializes a stream used by `getservent' to read from the services database. The next use of `getservent' will return the first entry. The return value is unspecified. -- procedure: getservent Return the next entry from the services database. -- procedure: endservent Close the stream used by `getservent'. The return value is unspecified.  File: guile-ref.info, Node: Network sockets, Prev: Networking Databases, Up: Networking Network sockets =============== Socket ports can be created using `socket' and `socketpair'. The ports are initially unbuffered, to makes reading and writing to the same port more reliable. Buffered ports can be obtained with `duplicate-port', *Note Ports and File Descriptors::. These procedures convert Internet addresses and port values between "host" order and "network" order as required. The arguments and return values should be in "host" order. -- primitive: socket family style protocol Returns a new socket port of the type specified by FAMILY, STYLE and PROTOCOL. All three parameters are integers. Typical values for FAMILY are the values of `AF_UNIX' and `AF_INET'. Typical values for STYLE are the values of `SOCK_STREAM', `SOCK_DGRAM' and `SOCK_RAW'. PROTOCOL can be obtained from a protocol name using `getprotobyname'. A value of zero specifies the default protocol, which is usually right. A single socket port cannot by used for communication until it has been connected to another socket. -- primitive: socketpair family style protocol Returns a pair of connected (but unnamed) socket ports of the type specified by FAMILY, STYLE and PROTOCOL. Many systems support only socket pairs of the `AF_UNIX' family. Zero is likely to be the only meaningful value for PROTOCOL. -- primitive: getsockopt socket level optname Returns the value of a particular socket option for the socket port SOCKET. LEVEL is an integer code for type of option being requested, e.g., `SOL_SOCKET' for socket-level options. OPTNAME is an integer code for the option required and should be specified using one of the symbols `SO_DEBUG', `SO_REUSEADDR' etc. The returned value is typically an integer but `SO_LINGER' returns a pair of integers. -- primitive: setsockopt socket level optname value Sets the value of a particular socket option for the socket port SOCKET. LEVEL is an integer code for type of option being set, e.g., `SOL_SOCKET' for socket-level options. OPTNAME is an integer code for the option to set and should be specified using one of the symbols `SO_DEBUG', `SO_REUSEADDR' etc. VALUE is the value to which the option should be set. For most options this must be an integer, but for `SO_LINGER' it must be a pair. The return value is unspecified. -- primitive: shutdown socket how Sockets can be closed simply by using `close-port'. The `shutdown' procedure allows reception or tranmission on a connection to be shut down individually, according to the parameter HOW: 0 Stop receiving data for this socket. If further data arrives, reject it. 1 Stop trying to transmit data from this socket. Discard any data waiting to be sent. Stop looking for acknowledgement of data already sent; don't retransmit it if it is lost. 2 Stop both reception and transmission. The return value is unspecified. -- primitive: connect socket family address [arg ...] Initiates a connection from SOCKET to the address specified by ADDRESS and possibly ARG .... The format required for ADDRESS and ARG ... depends on the family of the socket. For a socket of family `AF_UNIX', only `address' is specified and must be a string with the filename where the socket is to be created. For a socket of family `AF_INET', `address' must be an integer Internet host address and ARG ... must be a single integer port number. The return value is unspecified. -- primitive: bind socket family address arg ... Assigns an address to the socket port SOCKET. Generally this only needs to be done for server sockets, so they know where to look for incoming connections. A socket without an address will be assigned one automatically when it starts communicating. The format of ADDRESS and ARG ... depends on the family of the socket. For a socket of family `AF_UNIX', only ADDRESS is specified and must be a string with the filename where the socket is to be created. For a socket of family `AF_INET', ADDRESS must be an integer Internet host address and ARG ... must be a single integer port number. The values of the following variables can also be used for ADDRESS: -- Variable: INADDR_ANY Allow connections from any address. -- Variable: INADDR_LOOPBACK The address of the local host using the loopback device. -- Variable: INADDR_BROADCAST The broadcast address on the local network. -- Variable: INADDR_NONE No address. The return value is unspecified. -- primitive: listen socket backlog This procedure enables SOCKET to accept connection requests. BACKLOG is an integer specifying the maximum length of the queue for pending connections. If the queue fills, new clients will fail to connect until the server calls `accept' to accept a connection from the queue. The return value is unspecified. -- primitive: accept socket Accepts a connection on a bound, listening socket SOCKET. If there are no pending connections in the queue, it waits until one is available unless the non-blocking option has been set on the socket. The return value is a pair in which the CAR is a new socket port for the connection and the CDR is an object with address information about the client which initiated the connection. If the address is not available then the CDR will be an empty vector. SOCKET does not become part of the connection and will continue to accept new requests. The following functions take a socket address object, as returned by `accept' and other procedures, and return a selected component. `sockaddr:fam' The socket family, typically equal to the value of `AF_UNIX' or `AF_INET'. `sockaddr:path' If the socket family is `AF_UNIX', returns the path of the filename the socket is based on. `sockaddr:addr' If the socket family is `AF_INET', returns the Internet host address. `sockaddr:port' If the socket family is `AF_INET', returns the Internet port number. -- primitive: getsockname socket Returns the address of SOCKET, in the same form as the object returned by `accept'. On many systems the address of a socket in the `AF_FILE' namespace cannot be read. -- primitive: getpeername socket Returns the address of the socket that the socket SOCKET is connected to, in the same form as the object returned by `accept'. On many systems the address of a socket in the `AF_FILE' namespace cannot be read. -- primitive: recv! socket buf [flags] Receives data from the socket port SOCKET. SOCKET must already be bound to the address from which data is to be received. BUF is a string into which the data will be written. The size of BUF limits the amount of data which can be received: in the case of packet protocols, if a packet larger than this limit is encountered then some data will be irrevocably lost. The optional FLAGS argument is a value or bitwise OR of MSG_OOB, MSG_PEEK, MSG_DONTROUTE etc. The value returned is the number of bytes read from the socket. Note that the data is read directly from the socket file descriptor: any unread buffered port data is ignored. -- primitive: send socket message [flags] Transmits the string MESSAGE on the socket port SOCKET. SOCKET must already be bound to a destination address. The value returned is the number of bytes transmitted -- it's possible for this to be less than the length of MESSAGE if the socket is set to be non-blocking. The optional FLAGS argument is a value or bitwise OR of MSG_OOB, MSG_PEEK, MSG_DONTROUTE etc. Note that the data is written directly to the socket file descriptor: any unflushed buffered port data is ignored. -- primitive: recvfrom! socket buf [flags] [start] [end] Returns data from the socket port SOCKET and also information about where the data was received from. SOCKET must already be bound to the address from which data is to be received. `buf', is a string into which the data will be written. The size of BUF limits the amount of data which can be received: in the case of packet protocols, if a packet larger than this limit is encountered then some data will be irrevocably lost. The optional FLAGS argument is a value or bitwise OR of MSG_OOB, MSG_PEEK, MSG_DONTROUTE etc. The value returned is a pair: the CAR is the number of bytes read from the socket and the CDR an address object in the same form as returned by `accept'. The START and END arguments specify a substring of BUF to which the data should be written. Note that the data is read directly from the socket file descriptor: any unread buffered port data is ignored. -- primitive: sendto socket message family address arg ... [flags] Transmits the string MESSAGE on the socket port SOCKET. The destination address is specified using the FAMILY, ADDRESS and ARG arguments, in a similar way to the `connect' procedure. The value returned is the number of bytes transmitted -- it's possible for this to be less than the length of MESSAGE if the socket is set to be non-blocking. The optional FLAGS argument is a value or bitwise OR of MSG_OOB, MSG_PEEK, MSG_DONTROUTE etc. Note that the data is written directly to the socket file descriptor: any unflushed buffered port data is ignored.  File: guile-ref.info, Node: System Identification, Next: Locales, Prev: Networking, Up: Top System Identification ********************* -- primitive: uname Returns an object with some information about the computer system the program is running on. The following procedures accept an object as returned by `uname' and return a selected component. `utsname:sysname' The name of the operating system. `utsname:nodename' The network name of the computer. `utsname:release' The current release level of the operating system implementation. `utsname:version' The current version level within the release of the operating system. `utsname:machine' A description of the hardware. -- primitive: software-type Return a symbol describing the current platform's operating system. This may be one of AIX, VMS, UNIX, COHERENT, WINDOWS, MS-DOS, OS/2, THINKC, AMIGA, ATARIST, MACH, or ACORN. Note that most varieties of Unix are considered to be simply "UNIX". That is because when a program depends on features that are not present on every operating system, it is usually better to test for the presence or absence of that specific feature. The return value of `software-type' should only be used for this purpose when there is no other easy or unambiguous way of detecting such features.  File: guile-ref.info, Node: Locales, Next: Expect, Prev: System Identification, Up: Top Locales ******* -- primitive: setlocale category [locale] If LOCALE is omitted, returns the current value of the specified locale category as a system-dependent string. CATEGORY should be specified using the values `LC_COLLATE', `LC_ALL' etc. Otherwise the specified locale category is set to the string LOCALE and the new value is returned as a system-dependent string. If LOCALE is an empty string, the locale will be set using envirionment variables.  File: guile-ref.info, Node: Expect, Next: The Scheme shell (scsh), Prev: Locales, Up: Top Expect ****** The macros in this section are made available with: (use-modules (ice-9 expect)) `expect' is a macro for selecting actions based on the output from a port. The name comes from a tool of similar functionality by Don Libes. Actions can be taken when a particular string is matched, when a timeout occurs, or when end-of-file is seen on the port. The `expect' macro is described below; `expect-strings' is a front-end to `expect' based on regexec (see the regular expression documentation). -- Macro: expect-strings clause ... By default, `expect-strings' will read from the current input port. The first term in each clause consists of an expression evaluating to a string pattern (regular expression). As characters are read one-by-one from the port, they are accumulated in a buffer string which is matched against each of the patterns. When a pattern matches, the remaining expression(s) in the clause are evaluated and the value of the last is returned. For example: (with-input-from-file "/etc/passwd" (lambda () (expect-strings ("^nobody" (display "Got a nobody user.\n") (display "That's no problem.\n")) ("^daemon" (display "Got a daemon user.\n"))))) The regular expression is compiled with the `REG_NEWLINE' flag, so that the ^ and $ anchors will match at any newline, not just at the start and end of the string. There are two other ways to write a clause: The expression(s) to evaluate can be omitted, in which case the result of the regular expression match (converted to strings, as obtained from regexec with match-pick set to "") will be returned if the pattern matches. The symbol `=>' can be used to indicate that the expression is a procedure which will accept the result of a successful regular expression match. E.g., ("^daemon" => write) ("^d\\(aemon\\)" => (lambda args (for-each write args))) ("^da\\(em\\)on" => (lambda (all sub) (write all) (newline) (write sub) (newline))) The order of the substrings corresponds to the order in which the opening brackets occur. A number of variables can be used to control the behaviour of `expect' (and `expect-strings'). By default they are all bound at the top level to the value `#f', which produces the default behaviour. They can be redefined at the top level or locally bound in a form enclosing the expect expression. `expect-port' A port to read characters from, instead of the current input port. `expect-timeout' `expect' will terminate after this number of seconds, returning `#f' or the value returned by expect-timeout-proc. `expect-timeout-proc' A procedure called if timeout occurs. The procedure takes a single argument: the accumulated string. `expect-eof-proc' A procedure called if end-of-file is detected on the input port. The procedure takes a single argument: the accumulated string. `expect-char-proc' A procedure to be called every time a character is read from the port. The procedure takes a single argument: the character which was read. Here's an example using all of the variables: (let ((expect-port (open-input-file "/etc/passwd")) (expect-timeout 1) (expect-timeout-proc (lambda (s) (display "Times up!\n"))) (expect-eof-proc (lambda (s) (display "Reached the end of the file!\n"))) (expect-char-proc display)) (expect-strings ("^nobody" (display "Got a nobody user\n")))) -- Macro: expect clause ... `expect' is used in the same way as `expect-strings', but tests are specified not as patterns, but as procedures. The procedures are called in turn after each character is read from the port, with the value of the accumulated string as the argument. The test is successful if the procedure returns a non-false value. If the `=>' syntax is used, then if the test succeeds it must return a list containing the arguments to be provided to the corresponding expression. In the following example, a string will only be matched at the beginning of the file: (let ((expect-port (open-input-file "/etc/passwd"))) (expect ((lambda (s) (string=? s "fnord!")) (display "Got a nobody user!\n")))) The control variables described for `expect-strings' can also be used with `expect'.  File: guile-ref.info, Node: The Scheme shell (scsh), Next: Tcl/Tk Interface, Prev: Expect, Up: Top The Scheme shell (scsh) *********************** An incomplete port of the Scheme shell (scsh) 0.5.1 is available for Guile. The idea is to allow Scheme code using scsh interfaces to be run inside the Guile interpreter. For information about scsh on the Web see . The original scsh is available by ftp from . The scsh code is distributed as a separate module, guile-scsh, which must be installed somewhere in Guile's load path before it can be used. This is similar to the installation of slib (you may want to install that first, since it's needed before scsh can run in Guile: see *Note SLIB:: for details). This port of scsh does not currently use the Guile module system, but can be initialized with: (load-from-path "scsh/init")  File: guile-ref.info, Node: Tcl/Tk Interface, Next: A Portable C to Scheme Interface, Prev: The Scheme shell (scsh), Up: Top Tcl/Tk Interface ****************  File: guile-ref.info, Node: A Portable C to Scheme Interface, Next: gh preliminaries, Prev: Tcl/Tk Interface, Up: Top A Portable C to Scheme Interface ******************************** The Guile interpreter is based on Aubrey Jaffer's _SCM_ interpreter (*note SCM: a portable Scheme interpreter: (scm)Overview.) with some modifications to make it suitable as an embedded interpreter, and further modifications as Guile evolves. Part of the modification has been to provide a restricted interface to limit access to the SCM internals; this is called the `gh_' interface, or _libguile_ interface. If you are _programming with Guile_, you should only use the C subroutines described in this manual, which all begin with `gh_'. If instead you are _extending Guile_, you have the entire SCM source to play with. This manual will not help you at all, but you can consult Aubrey Jaffer's SCM manual (*note SCM: a portable Scheme interpreter: (scm)Internals.). If you are _adding a module to Guile_, I recommend that you stick to the `gh_' interface: this interface is guaranteed to not change drastically, while the SCM internals might change as Guile is developed. * Menu: * gh preliminaries:: * Data types and constants defined by gh:: * Starting and controlling the interpreter:: * Error messages:: * Executing Scheme code:: * Defining new Scheme procedures in C:: * Converting data between C and Scheme:: * Type predicates:: * Equality predicates:: * Memory allocation and garbage collection:: * Calling Scheme procedures from C:: * Mixing gh and scm APIs::  File: guile-ref.info, Node: gh preliminaries, Next: Data types and constants defined by gh, Prev: A Portable C to Scheme Interface, Up: Top gh preliminaries **************** To use gh, you must have the following toward the beginning of your C source: #include When you link, you will have to add at least `-lguile' to the list of libraries. If you are using more of Guile than the basic Scheme interpreter, you will have to add more libraries.  File: guile-ref.info, Node: Data types and constants defined by gh, Next: Starting and controlling the interpreter, Prev: gh preliminaries, Up: Top Data types and constants defined by gh ************************************** The following C constants and data types are defined in gh: -- Data type: SCM This is a C data type used to store all Scheme data, no matter what the Scheme type. Values are converted between C data types and the SCM type with utility functions described below (*note Converting data between C and Scheme::.). [FIXME: put in references to Jim's essay and so forth.] -- Constant: SCM_BOOL_T -- Constant: SCM_BOOL_F The _Scheme_ values returned by many boolean procedures in libguile. This can cause confusion because they are different from 0 and 1. In testing a boolean function in libguile programming, you must always make sure that you check the spec: `gh_' and `scm_' functions will usually return `SCM_BOOL_T' and `SCM_BOOL_F', but other C functions usually can be tested against 0 and 1, so programmers' fingers tend to just type `if (boolean_function()) { ... }' -- Constant: SCM_UNSPECIFIED This is an SCM object which does not correspond to any legal Scheme value. It can be used in C to terminate functions with variable numbers of arguments, such as `gh_list()'.  File: guile-ref.info, Node: Starting and controlling the interpreter, Next: Error messages, Prev: Data types and constants defined by gh, Up: Top Starting and controlling the interpreter **************************************** In almost every case, your first `gh_' call will be -- Function: void gh_enter (int ARGC, char *ARGV[], void (*MAIN_PROG)()) Starts up a Scheme interpreter with all the builtin Scheme primitives. `gh_enter()' never exits, and the user's code should all be in the `MAIN_PROG()' function. `argc' and `argv' will be passed to MAIN_PROG. -- Function: void main_prog (int ARGC, char *ARGV[]) This is the user's main program. It will be invoked by `gh_enter()' after Guile has been started up. Please note that `gh_enter' does not load `ice-9/boot-9.scm', which contains much of Guile's basic functionality, including some necessary parts of Scheme. This is a limitation, and it is only so because the basic Scheme language functions have not yet been separated from the higher-level functionality provided by the `ice-9/boot-9.scm' module. Here is a note from the Guile mailing list describing how to get around this problem if you want to run some Guile code before you invoke `gh_repl()'. It is a temporary solution, and a better way of handling the loading of `ice-9/boot-9.scm' will soon be introduced. The next problem is that boot-9.scm may only be executed once, otherwise you get a stack overflow. When entering the read-eval-print-loop (repl) with gh_repl, guile loads boot-9.scm. Thus, if you did load boot-9.scm yourself and then later enter the repl, guile will abort with a stack overflow. If you look a little into the guile mailing list archives, you can find a temporary solution to the problem which I posted quite some time ago. It's a trivial fix: 1) rename boot-9.scm into boot-9-tail.scm 2) create a new boot-9.scm, which only contains the following code: (if (not (defined? 'provide)) (primitive-load-path "ice-9/boot-9-tail.scm")) With this modification, boot-9.scm can be read several times. Also note that you can use `gh_repl' inside `gh_enter' if you want the program to be controled by a Scheme read--eval--print--loop. Invoking `gh_repl' will load `ice-9/boot-9.scm'. A convenience routine which enters the Guile interpreter with the standard Guile read--eval--print--loop ("REPL") is: -- Function: void gh_repl (int ARGC, char *ARGV[]) Enters the Scheme interpreter giving control to the Scheme REPL. Arguments are processed as if the Guile program `guile' were being invoked. Note that `gh_repl' should be used _inside_ `gh_enter', since any Guile interpreter calls are meaningless unless they happen in the context of the interpreter. Also note that when you use `gh_repl', your program will be controlled by Guile's REPL (which is written in Scheme and has many useful features). Use straight C code inside `gh_enter' if you want to maintain execution control in your C program. You will typically use `gh_enter' and `gh_repl()' when you want a Guile interpreter enhanced by your own libraries, but otherwise quite normal. For example, to build a Guile--derived program that includes some random number routines "GSL" (GNU Scientific Library), you would write a C program that looks like this: #include #include /* random number suite */ SCM gw_ran_seed(SCM s) { gsl_ran_seed(gh_scm2int(s)); return SCM_UNSPECIFIED; } SCM gw_ran_random() { SCM x; x = gh_ulong2scm(gsl_ran_random()); return x; } SCM gw_ran_uniform() { SCM x; x = gh_double2scm(gsl_ran_uniform()); return x; } SCM gw_ran_max() { return gh_double2scm(gsl_ran_max()); } void init_gsl() { /* random number suite */ gh_new_procedure("gsl-ran-seed", gw_ran_seed, 1, 0, 0); gh_new_procedure("gsl-ran-random", gw_ran_random, 0, 0, 0); gh_new_procedure("gsl-ran-uniform", gw_ran_uniform, 0, 0, 0); gh_new_procedure("gsl-ran-max", gw_ran_max, 0, 0, 0); } void main_prog (int argc, char *argv[]) { init_gsl(); gh_repl(argc, argv); } int main (int argc, char *argv[]) { gh_enter (argc, argv, main_prog); } Then, supposing the C program is in `guile-gsl.c', you could compile it with gcc -o guile-gsl guile-gsl.c -lguile -lgsl. The resulting program `guile-gsl' would have new primitive procedures `(gsl-ran-random)', `(gsl-ran-gaussian)' and so forth.  File: guile-ref.info, Node: Error messages, Next: Executing Scheme code, Prev: Starting and controlling the interpreter, Up: Top Error messages ************** [FIXME: need to fill this based on Jim's new mechanism]  File: guile-ref.info, Node: Executing Scheme code, Next: Defining new Scheme procedures in C, Prev: Error messages, Up: Top Executing Scheme code ********************* Once you have an interpreter running, you can ask it to evaluate Scheme code. There are two calls that implement this: -- Function: SCM gh_eval_str (char *SCHEME_CODE) This asks the interpreter to evaluate a single string of Scheme code, and returns the result of the last expression evaluated. Note that the line of code in SCHEME_CODE must be a well formed Scheme expression. If you have many lines of code before you balance parentheses, you must either concatenate them into one string, or use `gh_eval_file()'. -- Function: SCM gh_eval_file (char *FNAME) -- Function: SCM gh_load (char *FNAME) `gh_eval_file' is completely analogous to `gh_eval_str()', except that a whole file is evaluated instead of a string. Returns the result of the last expression evaluated. `gh_load' is identical to `gh_eval_file' (it's a macro that calls `gh_eval_file' on its argument). It is provided to start making the `gh_' interface match the R4RS Scheme procedures closely.  File: guile-ref.info, Node: Defining new Scheme procedures in C, Next: Converting data between C and Scheme, Prev: Executing Scheme code, Up: Top Defining new Scheme procedures in C *********************************** The real interface between C and Scheme comes when you can write new Scheme procedures in C. This is done through the routine -- Libguile high: SCM gh_new_procedure (char *PROC_NAME, SCM (*FN)(), int N_REQUIRED_ARGS, int N_OPTIONAL_ARGS, int RESTP) `gh_new_procedure' defines a new Scheme procedure. Its Scheme name will be PROC_NAME, it will be implemented by the C function (*FN)(), it will take at least N_REQUIRED_ARGS arguments, and at most N_OPTIONAL_ARGS extra arguments. When the RESTP parameter is 1, the procedure takes a final argument: a list of remaining parameters. `gh_new_procedure' returns an SCM value representing the procedure. The C function FN should have the form -- Libguile high: SCM fn (SCM REQ1, SCM REQ2, ..., SCM OPT1, SCM OPT2, ..., SCM REST_ARGS) The arguments are all passed as SCM values, so the user will have to use the conversion functions to convert to standard C types. Examples of C functions used as new Scheme primitives can be found in the sample programs `learn0' and `learn1'. *Rationale:* this is the correct way to define new Scheme procedures in C. The ugly mess of arguments is required because of how C handles procedures with variable numbers of arguments. *Note:* what about documentation strings? There are several important considerations to be made when writing the C routine (*FN)(). First of all the C routine has to return type `SCM'. Second, all arguments passed to the C funcion will be of type `SCM'. Third: the C routine is now subject to Scheme flow control, which means that it could be interrupted at any point, and then reentered. This means that you have to be very careful with operations such as allocating memory, modifying static data ... Fourth: to get around the latter issue, you can use `GH_DEFER_INTS' and `GH_ALLOW_INTS'. -- Macro: GH_DEFER_INTS -- Macro: GH_ALLOW_INTS These macros disable and reenable Scheme's flow control. They  File: guile-ref.info, Node: Converting data between C and Scheme, Next: Type predicates, Prev: Defining new Scheme procedures in C, Up: Top Converting data between C and Scheme ************************************ Guile provides mechanisms to convert data between C and Scheme. This allows new builtin procedures to understand their arguments (which are of type `SCM') and return values of type `SCM'. * Menu: * C to Scheme:: * Scheme to C::  File: guile-ref.info, Node: C to Scheme, Next: Scheme to C, Up: Converting data between C and Scheme C to Scheme =========== -- Function: SCM gh_bool2scm (int X) Returns `#f' if X is zero, `#t' otherwise. -- Function: SCM gh_ulong2scm (unsigned long X) -- Function: SCM gh_long2scm (long X) -- Function: SCM gh_double2scm (double X) -- Function: SCM gh_char2scm (char X) Returns a Scheme object with the value of the C quantity X. -- Function: SCM gh_str2scm (char *S, int LEN) Returns a new Scheme string with the (not necessarily null-terminated) C array S data. -- Function: SCM gh_str02scm (char *S) Returns a new Scheme string with the null-terminated C string S data. -- Function: SCM gh_set_substr (char *SRC, SCM DST, int START, int LEN) Copy LEN characters at SRC into the _existing_ Scheme string DST, starting at START. START is an index into DST; zero means the beginning of the string. If START + LEN is off the end of DST, signal an out-of-range error. -- Function: SCM gh_symbol2scm (char *NAME) Given a null-terminated string NAME, return the symbol with that name. -- Function: SCM gh_ints2scm (int *DPTR, int N) -- Function: SCM gh_doubles2scm (double *DPTR, int N) Make a scheme vector containing the N ints or doubles at memory location DPTR. -- Function: SCM gh_chars2byvect (char *DPTR, int N) -- Function: SCM gh_shorts2svect (short *DPTR, int N) -- Function: SCM gh_longs2ivect (long *DPTR, int N) -- Function: SCM gh_ulongs2uvect (ulong *DPTR, int N) -- Function: SCM gh_floats2fvect (float *DPTR, int N) -- Function: SCM gh_doubles2dvect (double *DPTR, int N) Make a scheme uniform vector containing the N chars, shorts, longs, unsigned longs, floats or doubles at memory location DPTR.  File: guile-ref.info, Node: Scheme to C, Prev: C to Scheme, Up: Converting data between C and Scheme Scheme to C =========== -- Function: int gh_scm2bool (SCM OBJ) -- Function: unsigned long gh_scm2ulong (SCM OBJ) -- Function: long gh_scm2long (SCM OBJ) -- Function: double gh_scm2double (SCM OBJ) -- Function: int gh_scm2char (SCM OBJ) These routines convert the Scheme object to the given C type. -- Function: char *gh_scm2newstr (SCM STR, int *LENP) Given a Scheme string STR, return a pointer to a new copy of its contents, followed by a null byte. If LENP is non-null, set `*LENP' to the string's length. This function uses malloc to obtain storage for the copy; the caller is responsible for freeing it. Note that Scheme strings may contain arbitrary data, including null characters. This means that null termination is not a reliable way to determine the length of the returned value. However, the function always copies the complete contents of STR, and sets *LENP to the true length of the string (when LENP is non-null). -- Function: void gh_get_substr (SCM str, char *return_str, int *lenp) Copy LEN characters at START from the Scheme string SRC to memory at DST. START is an index into SRC; zero means the beginning of the string. DST has already been allocated by the caller. If START + LEN is off the end of SRC, signal an out-of-range error. -- Function: char *gh_symbol2newstr (SCM SYM, int *LENP) Takes a Scheme symbol and returns a string of the form `"'symbol-name"'. If LENP is non-null, the string's length is returned in `*LENP'. This function uses malloc to obtain storage for the returned string; the caller is responsible for freeing it. -- Function: char *gh_scm2chars (SCM VECTOR, chars *RESULT) -- Function: short *gh_scm2shorts (SCM VECTOR, short *RESULT) -- Function: long *gh_scm2longs (SCM VECTOR, long *RESULT) -- Function: float *gh_scm2floats (SCM VECTOR, float *RESULT) -- Function: double *gh_scm2doubles (SCM VECTOR, double *RESULT) Copy the numbers in VECTOR to the array pointed to by RESULT and return it. If RESULT is NULL, allocate a double array large enough. VECTOR can be an ordinary vector, a weak vector, or a signed or unsigned uniform vector of the same type as the result array. For chars, VECTOR can be a string or substring. For floats and doubles, VECTOR can contain a mix of inexact and integer values. If VECTOR is of unsigned type and contains values too large to fit in the signed destination array, those values will be wrapped around, that is, data will be copied as if the destination array was unsigned.  File: guile-ref.info, Node: Type predicates, Next: Equality predicates, Prev: Converting data between C and Scheme, Up: Top Type predicates *************** These C functions mirror Scheme's type predicate procedures with one important difference. The C routines return C boolean values (0 and 1) instead of `SCM_BOOL_T' and `SCM_BOOL_F'. The Scheme notational convention of putting a `?' at the end of predicate procedure names is mirrored in C by placing `_p' at the end of the procedure. For example, `(pair? ...)' maps to `gh_pair_p(...)'. -- Function: int gh_boolean_p (SCM VAL) Returns 1 if VAL is a boolean, 0 otherwise. -- Function: int gh_symbol_p (SCM VAL) Returns 1 if VAL is a symbol, 0 otherwise. -- Function: int gh_char_p (SCM VAL) Returns 1 if VAL is a char, 0 otherwise. -- Function: int gh_vector_p (SCM VAL) Returns 1 if VAL is a vector, 0 otherwise. -- Function: int gh_pair_p (SCM VAL) Returns 1 if VAL is a pair, 0 otherwise. -- Function: int gh_procedure_p (SCM VAL) Returns 1 if VAL is a procedure, 0 otherwise. -- Function: int gh_list_p (SCM VAL) Returns 1 if VAL is a list, 0 otherwise. -- Function: int gh_inexact_p (SCM VAL) Returns 1 if VAL is an inexact number, 0 otherwise. -- Function: int gh_exact_p (SCM VAL) Returns 1 if VAL is an exact number, 0 otherwise.  File: guile-ref.info, Node: Equality predicates, Next: Memory allocation and garbage collection, Prev: Type predicates, Up: Top Equality predicates ******************* These C functions mirror Scheme's equality predicate procedures with one important difference. The C routines return C boolean values (0 and 1) instead of `SCM_BOOL_T' and `SCM_BOOL_F'. The Scheme notational convention of putting a `?' at the end of predicate procedure names is mirrored in C by placing `_p' at the end of the procedure. For example, `(equal? ...)' maps to `gh_equal_p(...)'. -- Function: int gh_eq_p (SCM x, SCM y) Returns 1 if X and Y are equal in the sense of Scheme's `eq?' predicate, 0 otherwise. -- Function: int gh_eqv_p (SCM x, SCM y) Returns 1 if X and Y are equal in the sense of Scheme's `eqv?' predicate, 0 otherwise. -- Function: int gh_equal_p (SCM x, SCM y) Returns 1 if X and Y are equal in the sense of Scheme's `equal?' predicate, 0 otherwise. -- Function: int gh_string_equal_p (SCM S1, SCM S2) Returns 1 if the strings S1 and S2 are equal, 0 otherwise. -- Function: int gh_null_p (SCM L) Returns 1 if L is an empty list or pair; 0 otherwise.  File: guile-ref.info, Node: Memory allocation and garbage collection, Next: Calling Scheme procedures from C, Prev: Equality predicates, Up: Top Memory allocation and garbage collection ****************************************