4

我想为printfChez Scheme 中的 C 函数编写一个 FFI,使用foreign-procedure. 但我不知道我应该把什么作为签名,因为printf函数中的最后一个参数是一个可变参数。这是我的代码:

(import (chezscheme))

(define (print-format)
    (foreign-procedure "printf" 
        (string void*) int)) ;; <-- Here, the type format is "(arg arg ...) ret"

(print-format "Hello, %s!" "Ryan")

我也试过这个也无济于事:

(define (print-format . args)
    (foreign-procedure "printf" 
        (string args) int))

这也不起作用:

(define (print-format)
    (foreign-procedure "printf" 
        (string ...) int))

如何在函数签名中指定可变参数foreign-procedure

4

1 回答 1

3

虽然它不是最终的解决方案,但您可以使用宏来为系统调用提供可变数量的参数。

create-list用于为foreign-procedure 系统调用提供适当数量的参数。

比如宏调用

(print-format "Hello %s and %s" "Ryan" "Greg")

扩展为

((foreign-procedure "printf" (string string string) int) "Hello %s and %s" "Ryan" "Greg")

(define create-list
  (lambda (element n)
    "create a list by replicating element n times"
    (letrec ((helper
           (lambda (lst element n)
             (cond ((zero? n) lst)
                   (else
                    (helper
                     (cons element lst) element (- n 1)))))))
      (helper '() element n))))

(define-syntax print-format
  (lambda (x)
    (syntax-case x ()
      ((_ cmd ...)
       (with-syntax
        ((system-call-spec
          (syntax
           (create-list 'string
                        (length (syntax (cmd ...)))))))
        (with-syntax
         ((proc (syntax
                 (eval
                  `(foreign-procedure "printf"
                                      (,@system-call-spec) int)))))
         (syntax
          (proc cmd ...))))))))

(print-format "Hello %s!" "Ryan")
(print-format "Hello %s and %s" "Ryan" "Greg")

于 2020-04-05T17:11:58.940 回答