我想使用printf
在Chez Scheme中为C的foreign-procedure
函数编写一个FFI。但由于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
的函数签名中指定可变参数?
答案 0 :(得分:2)
尽管这不是最终的解决方案, 您可以使用宏来容纳可变数字 系统调用的参数设置。
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")