Skip to content

Instantly share code, notes, and snippets.

@lagagain
Created December 11, 2018 11:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lagagain/c145d35b5516cd138c39a57737d35093 to your computer and use it in GitHub Desktop.
Save lagagain/c145d35b5516cd138c39a57737d35093 to your computer and use it in GitHub Desktop.
[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