jna.clj 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. ;;; $OpenBSD: jna.clj,v 1.2 2016/04/18 17:33:12 jasper Exp $
  2. ;;; Basic set of JNA tests for use with Clojure
  3. (gen-interface
  4. :name jna.CLibrary
  5. :extends [com.sun.jna.Library]
  6. :methods [[printf [String] void]])
  7. (def libc (com.sun.jna.Native/loadLibrary "c" jna.CLibrary))
  8. (.printf libc "Hello, World\n")
  9. (defn- get-function [s]
  10. `(com.sun.jna.Function/getFunction ~(namespace s) ~(name s)))
  11. (defmacro jna-call
  12. "Call a native library function"
  13. [return-type function-symbol & args]
  14. `(.invoke ~(get-function function-symbol) ~return-type (to-array [~@args])))
  15. (jna-call Integer c/printf "-> %d\n" 42)
  16. ; Write a macro that wraps a native library function call
  17. (defmacro jna-func
  18. [ret-type func-symbol]
  19. `(let [func# ~(get-function func-symbol)]
  20. (fn [& args#]
  21. (.invoke func# ~ret-type (to-array args#)))))
  22. (def c-printf (jna-func Integer c/printf))
  23. (c-printf "int: %d\nfloat: %.2f\n" 42 42.0)
  24. (defmacro jna-malloc [size]
  25. `(let [buffer# (java.nio.ByteBuffer/allocateDirect ~size)
  26. pointer# (com.sun.jna.Native/getDirectBufferPointer buffer#)]
  27. (.order buffer# java.nio.ByteOrder/LITTLE_ENDIAN)
  28. {:pointer pointer# :buffer buffer#}))
  29. (let [struct (jna-malloc 44)]
  30. (jna-call Integer c/statvfs "/tmp" (:pointer struct))
  31. (let [fbsize (.getInt (:buffer struct))
  32. frsize (.getInt (:buffer struct) 4)
  33. blocks (.getInt (:buffer struct) 8)
  34. bfree (.getInt (:buffer struct) 12)
  35. bavail (.getInt (:buffer struct) 16)]
  36. (c-printf "# ignore statvfs\n")))