Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Initial version

  • Loading branch information...
commit 61a1de90d7f3274b90d5a9967115553a16619e34 0 parents
@Chouser authored
Showing with 43 additions and 0 deletions.
  1. +43 −0 src/net/n01se/clojure_jna.clj
43 src/net/n01se/clojure_jna.clj
@@ -0,0 +1,43 @@
+; Copyright (c) Chris Houser, May 2009. All rights reserved.
+; The use and distribution terms for this software are covered by the
+; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
+; which can be found in the file epl-v10.html at the root of this distribution.
+; By using this software in any fashion, you are agreeing to be bound by
+; the terms of this license.
+; You must not remove this notice, or any other, from this software.
+
+(ns
+ #^{:author "Chris Houser"
+ :doc "Dynamically load and use native C libs from Clojure using JNA"}
+ net.n01se.clojure-jna)
+
+(defn- get-function [s]
+ `(com.sun.jna.Function/getFunction ~(namespace s) ~(name s)))
+
+(defmacro jna-invoke
+ "Call a native library function:
+ (jna-invoke Integer c/printf \"My number: %d\\n\" 5)"
+ [return-type function-symbol & args]
+ `(.invoke ~(get-function function-symbol) ~return-type (to-array [~@args])))
+
+(defmacro jna-fn
+ "Return a Clojure function that wraps a native library function:
+ (def c-printf (jna-fn Integer c/printf))
+ (c-printf \"My number: %d\\n\" 5)"
+ [return-type function-symbol]
+ `(let [func# ~(get-function function-symbol)]
+ (fn [& args#]
+ (.invoke func# ~return-type (to-array args#)))))
+
+(defmacro jna-ns
+ "Create a namespace full of Clojure functions that wrap functions from
+ a native library:
+ (jna-ns native-c c [Integer printf, Integer open, Integer close])
+ (native-c/printf \"one %s two\\n\" \"hello\")"
+ [new-ns libname fnspecs]
+ `(do
+ (create-ns '~new-ns)
+ ~@(for [[return-type fn-name] (partition 2 fnspecs)]
+ `(intern '~new-ns '~fn-name
+ (jna-fn ~return-type ~(symbol (str libname) (str fn-name)))))
+ (the-ns '~new-ns)))
Please sign in to comment.
Something went wrong with that request. Please try again.