c - Chez Scheme 中的 FFI,用于具有可变参数 (varargs) 的 C 函数
问题描述
我想为printf
Chez 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
?
解决方案
虽然它不是最终的解决方案,但您可以使用宏来为系统调用提供可变数量的参数。
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")
推荐阅读
- python - openpyxl 只读模式不能 iter_cols
- python - 熊猫数据透视表输出具有整数和浮点数
- python - 数据库中不存在表“登录”
- python - 为什么re.sub在python中替换后添加空格?如何摆脱空间?
- java - 在 Java 进程中使用 Micrometer 计时器?
- rabbitmq - Yocto 项目 rabbitmq-server 配方构建
- c++ - 为什么在使用 lambda 递归时总是需要 [&]?
- c# - Java 验证签名 C# 等效
- javascript - 在 Console 日志的返回值中返回 undefiend
- laravel - 在laravel中以多种形式验证组中的至少一个复选框