Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
[practice] [Common Lisp] CFFI - c-printf example (Common Lisp)
(require :cffi)
(defpackage my-example
(:use :cl :cffi))
(in-package my-example)
;; example: direct call
(foreign-funcall "printf" :string (format nil "%s: %d~%") ;; need change ~% to \0 in c.(end for string)
:string "Hello"
:int 10
:int) ;; foreign return type
;; define a foreign function, then call it
(defcfun ("printf" c-printf) :int ;; :int is return type
(format :string) ;; the necessary arg
&rest) ;; accept other args
(c-printf (format nil "%s: %d~%")
:string "Hello" ;; other args need give the types
:int 10)
;; define a function to auto concate "~%" to format
(defmacro printf (format &rest type-and-args)
(let ((new-format (concatenate 'string format "~%")))
`(c-printf (format nil ,new-format) ,@type-and-args)))
(printf "%s:%d~%"
:string "Hello"
:int 10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment