Java Native Access

Last updated
Java Native Access
Original author(s) Todd Fast, Timothy Wall, Liang Chen
Initial releaseMay 9, 2007 (2007-05-09)
Stable release
5.14.0 / December 10, 2023;3 months ago (2023-12-10) [1]
Repository
Written in C and Java
Operating system Windows, macOS, Android, AIX, FreeBSD, Linux, OpenBSD, Solaris, Windows Mobile
Platform Java 1.4 or later (for JNA 3.5.2 or earlier), Java 1.6 for JNA 4.0.0 and later
Size 1.83 MB (archived)
Type Software Library
License LGPL version 2.1 or later and (from version 4.0 onward) the Apache Software License, version 2.0
Website github.com/java-native-access/jna

Java Native Access (JNA) is a community-developed library that provides Java programs easy access to native shared libraries without using the Java Native Interface (JNI). JNA's design aims to provide native access in a natural way with a minimum of effort. Unlike JNI, no boilerplate or generated glue code is required.

Contents

Architecture

The JNA library uses a small native library called foreign function interface library (libffi) to dynamically invoke native code. The JNA library uses native functions allowing code to load a library by name and retrieve a pointer to a function within that library, and uses libffi library to invoke it, all without static bindings, header files, or any compile phase. The developer uses a Java interface to describe functions and structures in the target native library. This makes it quite easy to take advantage of native platform features without incurring the high development overhead of configuring and building JNI code.

JNA is built and tested on macOS, Microsoft Windows, FreeBSD / OpenBSD, Solaris, Linux, AIX, Windows Mobile, and Android. It is also possible to tweak and recompile the native build configurations to make it work on most other platforms that run Java.

Mapping types

The following table shows an overview of types mapping between Java and native code and supported by the JNA library. [2]

Native TypeSizeJava TypeCommon Windows Types
char 8-bit integer byte BYTE, TCHAR
short 16-bit integer short WORD
wchar_t 16/32-bit character char TCHAR
int 32-bit integer int DWORD
int boolean valuebooleanBOOL
long 32/64-bit integerNativeLongLONG
long long 64-bit integer long __int64
float 32-bit FP float
double 64-bit FP double
char*C stringStringLPCSTR
void*pointerPointerLPVOID, HANDLE, LPXXX

Note: The meaning of TCHAR changes between char and wchar_t according to some preprocessor definitions. LPCTSTR follows.

Memory byte alignment for data structures

Native libraries have no standardized memory byte alignment flavor. JNA defaults to an OS platform specific setting, that can be overridden by a library specific custom alignment. If the alignment details are not given in the documentation of the native library, the correct alignment must be determined by trial and error during implementation of the Java wrapper.

Example

The following program loads the local C standard library implementation and uses it to call the printf function.

Note: The following code is portable and works the same on Windows and POSIX (Linux / Unix / macOS) platforms.

importcom.sun.jna.Library;importcom.sun.jna.Native;importcom.sun.jna.Platform;/** Simple example of native library declaration and usage. */publicclassHelloWorld{publicinterfaceCLibraryextendsLibrary{CLibraryINSTANCE=(CLibrary)Native.loadLibrary((Platform.isWindows()?"msvcrt":"c"),CLibrary.class);voidprintf(Stringformat,Object...args);}publicstaticvoidmain(String[]args){CLibrary.INSTANCE.printf("Hello, World\n");for(inti=0;i<args.length;i++){CLibrary.INSTANCE.printf("Argument %d: %s\n",i,args[i]);}}}

The following program loads the C POSIX library and uses it to call the standard mkdir function.

Note: The following code is portable and works the same on POSIX standards platforms.

importcom.sun.jna.Library;importcom.sun.jna.Native;/** Simple example of native C POSIX library declaration and usage. */publicclassExampleOfPOSIX{publicinterfacePOSIXextendsLibrary{publicintchmod(Stringfilename,intmode);publicintchown(Stringfilename,intuser,intgroup);publicintrename(Stringoldpath,Stringnewpath);publicintkill(intpid,intsignal);publicintlink(Stringoldpath,Stringnewpath);publicintmkdir(Stringpath,intmode);publicintrmdir(Stringpath);}publicstaticvoidmain(String[]args){// It is possible to load msvcrt for its partial POSIX support on Windows...POSIXposix=(POSIX)Native.loadLibrary("c",POSIX.class);// but it will still fail on Windows due to /tmp being missing.posix.mkdir("/tmp/newdir",0777);posix.rename("/tmp/newdir","/tmp/renamedir");}}

The program below loads the Kernel32.dll and uses it to call the Beep and Sleep functions.

Note: The following code works only on Windows platforms.

importcom.sun.jna.Library;importcom.sun.jna.Native;/** Simple example of Windows native library declaration and usage. */publicclassBeepExample{publicinterfaceKernel32extendsLibrary{// FREQUENCY is expressed in hertz and ranges from 37 to 32767// DURATION is expressed in millisecondspublicbooleanBeep(intFREQUENCY,intDURATION);publicvoidSleep(intDURATION);}publicstaticvoidmain(String[]args){Kernel32lib=(Kernel32)Native.loadLibrary("kernel32",Kernel32.class);lib.Beep(698,500);lib.Sleep(500);lib.Beep(698,500);}}

Performance

Benchmarks show JNA averages ten times slower than JNI. [3] [4] [5]

Alternatives

Several alternatives are emerging. [6] The tradeoff between easy to implement the code and runtime speed should be considered when evaluating these software development tools. The addition of third party dependent libraries that must be redistributed and updated is another factor in the decision of which tool to use. The Technology readiness level should also be considered.

See also

Related Research Articles

Common Intermediate Language (CIL), formerly called Microsoft Intermediate Language (MSIL) or Intermediate Language (IL), is the intermediate language binary instruction set defined within the Common Language Infrastructure (CLI) specification. CIL instructions are executed by a CIL-compatible runtime environment such as the Common Language Runtime. Languages which target the CLI compile to CIL. CIL is object-oriented, stack-based bytecode. Runtimes typically just-in-time compile CIL instructions into native code.

In software design, the Java Native Interface (JNI) is a foreign function interface programming framework that enables Java code running in a Java virtual machine (JVM) to call and be called by native applications and libraries written in other languages such as C, C++ and assembly.

<span class="mw-page-title-main">D (programming language)</span> Multi-paradigm system programming language

D, also known as dlang, is a multi-paradigm system programming language created by Walter Bright at Digital Mars and released in 2001. Andrei Alexandrescu joined the design and development effort in 2007. Though it originated as a re-engineering of C++, D is now a very different language drawing inspiration from other high-level programming languages, notably Java, Python, Ruby, C#, and Eiffel.

<span class="mw-page-title-main">Swing (Java)</span> Java-based GUI toolkit

Swing is a GUI widget toolkit for Java. It is part of Oracle's Java Foundation Classes (JFC) – an API for providing a graphical user interface (GUI) for Java programs.

In computing, POSIX Threads, commonly known as pthreads, is an execution model that exists independently from a programming language, as well as a parallel execution model. It allows a program to control multiple different flows of work that overlap in time. Each flow of work is referred to as a thread, and creation and control over these flows is achieved by making calls to the POSIX Threads API. POSIX Threads is an API defined by the Institute of Electrical and Electronics Engineers (IEEE) standard POSIX.1c, Threads extensions .

<span class="mw-page-title-main">Java syntax</span> Set of rules defining correctly structured program

The syntax of Java is the set of rules defining how a Java program is written and interpreted.

In computer programming, an entry point is the place in a program where the execution of a program begins, and where the program has access to command line arguments.

A dynamic-link library (DLL) is a shared library in the Microsoft Windows or OS/2 operating system.

J/Direct was a technology included in some versions of Microsoft Java Virtual Machine, which allowed direct calls into the Windows API. J/Direct was specific of Microsoft's Virtual Machine, in replacement of the standard Java Native Interface (JNI).

A foreign function interface (FFI) is a mechanism by which a program written in one programming language can call routines or make use of services written or compiled in another one. An FFI is often used in contexts where calls are made into binary dynamic-link library.

Platform Invocation Services, commonly referred to as P/Invoke, is a feature of Common Language Infrastructure implementations, like Microsoft's Common Language Runtime, that enables managed code to call native code.

Haxe is a high-level cross-platform programming language and compiler that can produce applications and source code for many different computing platforms from one code-base. It is free and open-source software, released under the MIT License. The compiler, written in OCaml, is released under the GNU General Public License (GPL) version 2.

stdarg.h is a header in the C standard library of the C programming language that allows functions to accept an indefinite number of arguments. It provides facilities for stepping through a list of function arguments of unknown number and type. C++ provides this functionality in the header cstdarg.

<span class="mw-page-title-main">Vala (programming language)</span> Programming language

Vala is an object-oriented programming language with a self-hosting compiler that generates C code and uses the GObject system.

Wrapper libraries consist of a thin layer of code which translates a library's existing interface into a compatible interface. This is done for several reasons:

Getopt is a C library function used to parse command-line options of the Unix/POSIX style. It is a part of the POSIX specification, and is universal to Unix-like systems. It is also the name of a Unix program for parsing command line arguments in shell scripts.

Different command-line argument parsing methods are used by different programming languages to parse command-line arguments.

Nemerle is a general-purpose, high-level, statically typed programming language designed for platforms using the Common Language Infrastructure (.NET/Mono). It offers functional, object-oriented, aspect-oriented, reflective and imperative features. It has a simple C#-like syntax and a powerful metaprogramming system.

In software engineering, the module pattern is a design pattern used to implement the concept of software modules, defined by modular programming, in a programming language with incomplete direct support for the concept.

Objective-C is a high-level general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTSTEP operating system. Due to Apple macOS’s direct lineage from NeXTSTEP, Objective-C was the standard programming language used, supported, and promoted by Apple for developing macOS and iOS applications until the introduction of the Swift programming language in 2014.

References

  1. "Release 5.14.0". GitHub . 2023-01-14.
  2. "Default Type Mappings". jna.dev.java.net. Retrieved 2011-08-02.
  3. "JNI vs JNA performance". Reddit. Retrieved 30 March 2023.
  4. "JNI vs JNA benchmark". Medium. Retrieved 30 March 2023.
  5. "JNI vs JNA performance benchmark". Stack Overflow. Stack Overflow. Retrieved 30 March 2023.
  6. "JNI alternatives emerging". OKTA. Retrieved 30 March 2023.