| How to extend C programs with Guile | ||
|---|---|---|
| <<< Previous | Next >>> | |
In this chapter, I'll deal with the topic of functions that take variable numbers of arguments.
Allow me to reiterate my statement that if one wants to wrap many C functions, it is worth considering the g-wrap or swigframeworks. But for programs with only a few functions to wrap for Guile, it is easy enough to do it by hand.
To declare a Scheme function with variable numbers of arguments, a space delimited period is placed before the last argument in the function declaration. The function may then be called with any number of extra arguments. The extra arguments are place in a list. Consider Example 1> that defines a simple function with one required argument and one variable argument. When run, it outputs Example 2>. If called with only one argument, the variable argument list is empty. If called with more than one argument, the remaining arguments appear as a list in the second argument.
Example 1. A Guile Function with Variable Arguments
#!/usr/local/bin/guile -s
!#
(define (varfunc arg1 . arg2)
(begin
(display "arg1: ")
(write arg1)
(newline)
(display "arg2: ")
(write arg2)
(newline)
(newline)))
(varfunc 10)
(varfunc 10 20)
(varfunc 10 20 30 )
|
Example 2. A Guile Function with Variable Arguments
arg1: 10
arg2: ()
arg1: 10
arg2: (20)
arg1: 10
arg2: (20 30)
|
Calling a function with variable number of arguments from C requires no special new processing. When calling from C, just as when calling from Guile, there is no need to box up the variable arguments into a list before calling the function.
To call the function using scm_c_eval_string, just create a an approproate command string to use, and then evaluate it as described in the section called Calling Guile functions from C in the chapter called Functions I> and demonstrated in Example 4 in the section called Calling Guile Functions from C, an Example in the chapter called Functions I>. The gentle reader may have noticed that we already called a function with variable number of arguments in Example 4 in the section called Conventional Arrays in the chapter called Arrays, and other compound data types>
To call the function using scm_call_n, look up the procedure by name and then call it as described in the section called Calling Guile functions from C in the chapter called Functions I> and demonstrated in Example 1 in the section called Calling Guile Functions from C, an Example in the chapter called Functions I>.
| <<< Previous | Home | Next >>> |
| Interacting with Guile Compound Data Types in C | Calling a C Function with variable number of arguments from Guile |