Native library calls from Clojure via JNA

278 views
Skip to first unread message

Aaron Brooks

unread,
Sep 29, 2008, 2:09:04 PM9/29/08
to Clojure
All,

I've had success using JNA to call system libraries I thought I'd post
an example snippet in case it helps someone else. The below demo
requires a clojure-contrib.jar from http://sf.net/projects/clojure-contrib
and a jna.jar from
https://jna.dev.java.net/ (be sure it's actually, jna.jar not one of
the platform specific jar -- I got stuck for a while trying to get the
platform specific jar working when the generic jna.jar works fine).
The below is *NIX specific and runs fine on my Gentoo Linux x86_64
system with Java 1.6.0.

JNA is slower than a hard coded JNI interface but for the 99% of
system poking that one might want to do (iNotify, ioctls, UDS, etc.)
it should work very nicely. Feel free to ask questions in case the
example isn't clear but be forewarned -- the below encapsulates 100%
of my JNA + Clojure knowledge so far. ;-)

; glibc from Clojure via JNA
(ns jnatest
(:import (com.sun.jna Library Native))
(:use (clojure.contrib gen-interface)))

(gen-and-load-interface 'jnatest.CLibrary [Library]
['getppid [] Integer]
['getpid [] Integer]
['sleep [Integer] Void])

(def glibc (Native/loadLibrary "c" jnatest.CLibrary))

(println "Parent's PID: " (.getppid glibc))
(println "My PID: " (.getpid glibc))

(println "Now show that we can sleep:")
(time (.sleep glibc 2))

Allen Rohner

unread,
Sep 29, 2008, 3:02:57 PM9/29/08
to Clojure


On Sep 29, 1:09 pm, Aaron Brooks <aa...@brooks1.net> wrote:
> I've had success using JNA to call system libraries I thought I'd post
> an example snippet in case it helps someone else.

This looks very cool. I didn't know it would be this easy. Thanks for
the example.

Allen
Reply all
Reply to author
Forward
0 new messages