Java Native Access
Encyclopedia
Java Native Access provides Java
Java (Sun)
Java refers to several computer software products and specifications from Sun Microsystems, a subsidiary of Oracle Corporation, that together provide a system for developing application software and deploying it in a cross-platform environment...

 programs easy access to native shared libraries without using the Java Native Interface
Java Native Interface
The Java Native Interface is a programming framework that enables Java code running in a Java Virtual Machine to call and to be called by native applications and libraries written in other languages such as C, C++ and assembly.-Purpose and features:JNI enables one to write native methods to...

. JNA's design aims to provide native access in a natural way with a minimum of effort. No boilerplate
Boilerplate (text)
Boilerplate is any text that is or can be reused in new contexts or applications without being changed much from the original. Many computer programmers often use the term boilerplate code. A legal boilerplate is a standard provision in a contract....

 or generated glue code
Glue code
In programming, glue code is code that does not contribute any functionality towards meeting the program's requirements, but instead serves solely to "glue together" different parts of code that would not otherwise be compatible...

 is required.

Architecture

The JNA library uses a small native library called foreign function interface
Foreign function interface
A foreign function interface is a mechanism by which a program written in one programming language can call routines or make use of services written in another. The term comes from the specification for Common Lisp, which explicitly refers to the language features for inter-language calls as...

 library (libffi
Libffi
libffi is a foreign function interface library. It provides a C programming language interface for calling natively compiled functions given information about the target function at run time instead of compile time...

) 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
Libffi
libffi is a foreign function interface library. It provides a C programming language interface for calling natively compiled functions given information about the target function at run time instead of compile time...

 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 Mac OS X
Mac OS X
Mac OS X is a series of Unix-based operating systems and graphical user interfaces developed, marketed, and sold by Apple Inc. Since 2002, has been included with all new Macintosh computer systems...

, Microsoft Windows
Microsoft Windows
Microsoft Windows is a series of operating systems produced by Microsoft.Microsoft introduced an operating environment named Windows on November 20, 1985 as an add-on to MS-DOS in response to the growing interest in graphical user interfaces . Microsoft Windows came to dominate the world's personal...

, FreeBSD
FreeBSD
FreeBSD is a free Unix-like operating system descended from AT&T UNIX via BSD UNIX. Although for legal reasons FreeBSD cannot be called “UNIX”, as the direct descendant of BSD UNIX , FreeBSD’s internals and system APIs are UNIX-compliant...

 / OpenBSD
OpenBSD
OpenBSD is a Unix-like computer operating system descended from Berkeley Software Distribution , a Unix derivative developed at the University of California, Berkeley. It was forked from NetBSD by project leader Theo de Raadt in late 1995...

, Solaris, and Linux
Linux
Linux is a Unix-like computer operating system assembled under the model of free and open source software development and distribution. The defining component of any Linux system is the Linux kernel, an operating system kernel first released October 5, 1991 by Linus Torvalds...

. It is also possible to tweak and recompile the native build configurations to make it work on other platforms. For example, it is known to work on Windows Mobile
Windows Mobile
Windows Mobile is a mobile operating system developed by Microsoft that was used in smartphones and Pocket PCs, but by 2011 was rarely supplied on new phones. The last version is "Windows Mobile 6.5.5"; it is superseded by Windows Phone, which does not run Windows Mobile software.Windows Mobile is...

, even if it is not tested for this platform by the development team.

Mapping types

The following table shows an overview of types mapping between Java and native code and supported by the JNA library.
Native Type Size Java Language Type Common Windows Types
char
Character (computing)
In computer and machine-based telecommunications terminology, a character is a unit of information that roughly corresponds to a grapheme, grapheme-like unit, or symbol, such as in an alphabet or syllabary in the written form of a natural language....

8-bit integer byte
Byte
The byte is a unit of digital information in computing and telecommunications that most commonly consists of eight bits. Historically, a byte was the number of bits used to encode a single character of text in a computer and for this reason it is the basic addressable element in many computer...

BYTE, TCHAR
short 16-bit short short WORD
wchar t
Wide character
A wide character is a computer character datatype that generally has a size greater than the traditional 8-bit character. The increased datatype size allows for the use of larger coded character sets.-History:...

16/32-bit character char
Character (computing)
In computer and machine-based telecommunications terminology, a character is a unit of information that roughly corresponds to a grapheme, grapheme-like unit, or symbol, such as in an alphabet or syllabary in the written form of a natural language....

WCHAR, TCHAR
int
Integer (computer science)
In computer science, an integer is a datum of integral data type, a data type which represents some finite subset of the mathematical integers. Integral data types may be of different sizes and may or may not be allowed to contain negative values....

32-bit integer int
Integer (computer science)
In computer science, an integer is a datum of integral data type, a data type which represents some finite subset of the mathematical integers. Integral data types may be of different sizes and may or may not be allowed to contain negative values....

DWORD
int
Integer (computer science)
In computer science, an integer is a datum of integral data type, a data type which represents some finite subset of the mathematical integers. Integral data types may be of different sizes and may or may not be allowed to contain negative values....

boolean value boolean BOOL
long 32/64-bit integer NativeLong LONG
long long, __int64 64-bit integer long
float 32-bit FP float
double
Double precision
In computing, double precision is a computer number format that occupies two adjacent storage locations in computer memory. A double-precision number, sometimes simply called a double, may be defined to be an integer, fixed point, or floating point .Modern computers with 32-bit storage locations...

64-bit FP double
Double precision
In computing, double precision is a computer number format that occupies two adjacent storage locations in computer memory. A double-precision number, sometimes simply called a double, may be defined to be an integer, fixed point, or floating point .Modern computers with 32-bit storage locations...

char* C string String LPCTSTR
void* pointer Pointer LPVOID, HANDLE, LPXXX


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

Example

The following program loads the local C standard library
C standard library
The C Standard Library is the standard library for the programming language C, as specified in the ANSI C standard.. It was developed at the same time as the C POSIX library, which is basically a superset of it...

 implementation and uses it to call the printf
Printf
Printf format string refers to a control parameter used by a class of functions typically associated with some types of programming languages. The format string specifies a method for rendering an arbitrary number of varied data type parameter into a string...

function.

Note: The following code is portable and works the same on Windows
Microsoft Windows
Microsoft Windows is a series of operating systems produced by Microsoft.Microsoft introduced an operating environment named Windows on November 20, 1985 as an add-on to MS-DOS in response to the growing interest in graphical user interfaces . Microsoft Windows came to dominate the world's personal...

 and Linux
Linux
Linux is a Unix-like computer operating system assembled under the model of free and open source software development and distribution. The defining component of any Linux system is the Linux kernel, an operating system kernel first released October 5, 1991 by Linus Torvalds...

 / Unix
Unix
Unix is a multitasking, multi-user computer operating system originally developed in 1969 by a group of AT&T employees at Bell Labs, including Ken Thompson, Dennis Ritchie, Brian Kernighan, Douglas McIlroy, and Joe Ossanna...

 / Mac OS X
Mac OS X
Mac OS X is a series of Unix-based operating systems and graphical user interfaces developed, marketed, and sold by Apple Inc. Since 2002, has been included with all new Macintosh computer systems...

 platforms.


import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;

/** Simple example of native library declaration and usage. */
public class HelloWorld {
public interface CLibrary extends Library {
CLibrary INSTANCE = (CLibrary) Native.loadLibrary(
(Platform.isWindows ? "msvcrt" : "c"), CLibrary.class);
void printf(String format, Object... args);
}

public static void main(String[] args) {
CLibrary.INSTANCE.printf("Hello, World\n");
for (int i = 0; i < args.length; i++) {
CLibrary.INSTANCE.printf("Argument %d: %s\n", i, args[i]);
}
}
}


The following program loads the C POSIX library
C POSIX library
The C POSIX library is a specification of a C standard library for POSIX systems. It was developed at the same time as the ANSI C standard. Some effort was made to make POSIX compatible with standard C; POSIX includes additional functions to those introduced in standard C.- C POSIX library header...

 and uses it to call the standard mkdir
Mkdir
The mkdir command in the Unix, DOS, OS/2 and Microsoft Windows operating systems is used to make a new directory. In DOS, OS/2 and Windows the command is often abbreviated to md.-Usage:Normal usage is as straightforward as follows:...

function.

Note: The following code is portable and works the same on POSIX
POSIX
POSIX , an acronym for "Portable Operating System Interface", is a family of standards specified by the IEEE for maintaining compatibility between operating systems...

 standards platforms.


import com.sun.jna.Library;
import com.sun.jna.Native;

/** Simple example of native C POSIX library declaration and usage. */
public class exampleOfPOSIX {
public interface POSIX extends Library {
public int chmod(String filename, int mode);
public int chown(String filename, int user, int group);
public int rename(String oldpath, String newpath);
public int kill(int pid, int signal);
public int link(String oldpath, String newpath);
public int mkdir(String path, int mode);
public int rmdir(String path);
}

public static void main(String[] args) {
POSIX posix = (POSIX) Native.loadLibrary("c", POSIX.class);
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
Beep (sound)
A beep is a single tone onomatopoeia, generally made by a computer or a machine.-Use in computers:In some computer terminals, the ASCII character code 7, bell character, outputs an audible beep. The beep is also sometimes used to notify the user when the BIOS is not working or there is some other...

and Sleep
Sleep (operating system)
A computer program may sleep, which places it into an inactive state for a period of time. Eventually the expiration of an interval timer, or the receipt of a signal or interrupt causes the program to resume execution.- Usage :...

functions.

Note: The following code works only on Windows
Microsoft Windows
Microsoft Windows is a series of operating systems produced by Microsoft.Microsoft introduced an operating environment named Windows on November 20, 1985 as an add-on to MS-DOS in response to the growing interest in graphical user interfaces . Microsoft Windows came to dominate the world's personal...

 platforms.

import com.sun.jna.Library;
import com.sun.jna.Native;

/** Simple example of Windows native library declaration and usage. */
public class BeepExample {
public interface Kernel32 extends Library {
// FREQUENCY is expressed in hertz and ranges from 37 to 32767
// DURATION is expressed in milliseconds
public boolean Beep(int FREQUENCY, int DURATION);
public void Sleep(int DURATION);
}

public static void main(String[] args) {
Kernel32 lib = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class);
lib.Beep(698, 500);
lib.Sleep(500);
lib.Beep(698, 500);
}
}

Adoption

Java Native Access is known to be used in:
  • JRuby
    JRuby
    JRuby is a Java implementation of the Ruby programming language, being developed by the JRuby team. It is free software released under a three-way CPL/GPL/LGPL license...

     use JNA for POSIX
    POSIX
    POSIX , an acronym for "Portable Operating System Interface", is a family of standards specified by the IEEE for maintaining compatibility between operating systems...

     functionality
  • Freedom for Media in Java (FMJ)
  • IntelliJ IDEA
    IntelliJ IDEA
    IntelliJ IDEA is a commercial Java IDE by JetBrains. It is often simply referred to as "IDEA" or "IntelliJ."-History:The first version of IntelliJ IDEA was released in January 2001, and at the time was the only available Java IDE with advanced code navigation and code refactoring capabilities...

     IDE
    Integrated development environment
    An integrated development environment is a software application that provides comprehensive facilities to computer programmers for software development...

     by the company JetBrains
    JetBrains
    JetBrains is a Czech software development company with offices in Prague, Czech Republic; Saint Petersburg, Russia; Boston, USA and Munich, Germany...

  • OpenSearchServer
    OpenSearchServer
    OpenSearchServer is an open source application server allowing development of index-based applications like search engines. Available since April 2009 on SourceForge for download, OpenSearchServer was developed under the GPL v3 license and offers a series of full text lexical analyzers and can be...

     an open source search engine and web crawler
  • SVNKit
    SVNKit
    SVNKit is an Open Source, pure Java software library for working with the Subversion version control system. It is free to use on opensource projects but requires that you buy a commercial license to use to develop with commercial software...

     pure Java Subversion client library.
  • Videolan
    VideoLAN
    VideoLAN is a project that develops software for playing video and other media formats across a local area network . It originally developed two programs for media streaming, VideoLAN Client and VideoLAN Server , but most of the features of VLS have been incorporated into VLC, with the result...

     vlcj Java Multimedia Library.
  • Cyberduck
    Cyberduck
    Cyberduck is an open source FTP and SFTP, WebDAV, Cloud Files, Google Docs, and Amazon S3 client for Mac OS X and Windows licensed under the GPL. Cyberduck is written in the Java language and using the Cocoa user interface framework. It supports FTP/TLS , using AUTH TLS as well as directory...

     FTP, SFTP, WebDAV, Cloud Files & Amazon S3 Browser for Mac OS X.
  • Log4j
    Log4j
    Apache log4j is a Java-based logging utility. It was originally written by Ceki Gülcü and is now a project of the Apache Software Foundation. log4j is one of several Java Logging Frameworks....

    , a library of native log appenders (http://log4jna.codeplex.com).
  • Hudson
    Hudson (software)
    Hudson is a continuous integration tool written in Java, which runs in a servlet container, such as Apache Tomcat or the GlassFish application server. It supports SCM tools including CVS, Subversion, Git and Clearcase and can execute Apache Ant and Apache Maven based projects, as well as arbitrary...

     and Jenkins
    Jenkins (software)
    Jenkins, previously known as Hudson, is an open source continuous integration tool written in Java. The project renamed itself after a dispute with Oracle who claims the right to trademark the Hudson name and has applied for such a trademark as of December 2010...

     continuous integration servers.

See also

  • Java Native Interface
    Java Native Interface
    The Java Native Interface is a programming framework that enables Java code running in a Java Virtual Machine to call and to be called by native applications and libraries written in other languages such as C, C++ and assembly.-Purpose and features:JNI enables one to write native methods to...

  • P/Invoke
    Platform Invocation Services
    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.-Explicit:...

  • Foreign Function Interface Library
    Libffi
    libffi is a foreign function interface library. It provides a C programming language interface for calling natively compiled functions given information about the target function at run time instead of compile time...

  • JNAerator
    JNAerator
    JNAerator is a computer programming tool for the Java programming language which automatically generates the Java Native Access or BridJ code needed to call C and Objective-C libraries from Java code.It reads in ANSI C header files and emits Java code...

  • SWIG
    SWIG
    SWIG is an open source software tool used to connect computer programs or libraries written in C or C++ with scripting languages such as Lua, Perl, PHP, Python, R, Ruby, Tcl, and other languages like C#, Java, Modula-3, Objective Caml, Octave, and Scheme...

  • J/Invoke

External links


The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK