jna

16
. . JNA Java Native Access Robert Bachmann JSUG/JUGAT Meeting #59 1

Upload: robert-bachmann

Post on 07-May-2015

881 views

Category:

Technology


1 download

DESCRIPTION

http://jsug.at/wiki/Meeting_59

TRANSCRIPT

Page 1: JNA

.

......

JNAJava Native Access

Robert Bachmann

JSUG/JUGAT Meeting #59

1

Page 2: JNA

Motivation

• JNI (Java Native Interface) allows Javaprograms to call native code

• JNA is an open-source library that simpli esusing JNI (Java Native Interface)

2

Page 3: JNA

Reasons for “going native”

• Integration• Using operating system features (e.g: SWT)• Using architecture features (e.g: SSE, RdRand)• Performance (e.g: tomcat-native)

3

Page 4: JNA

Hello World with Windows API

int WINAPI MessageBoxA(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption,UINT uType

);

4

Page 5: JNA

JNI Example (1/3)

public class HelloJni {public native int msgBox(String s);

public static void main(String[] args) {System.loadLibrary(”HelloJni”);new HelloJni().msgBox(”Hello␣World!”);

}}

5

Page 6: JNA

JNI Example (2/3)

// generated by javah from HelloJni.class#include <jni.h>/* ... /*

* Class: HelloJni* Method: msgBox* Signature: (Ljava/lang/String;)I*/JNIEXPORT jintJNICALL Java_HelloJni_msgBox(JNIEnv *, jobject, jstring);

6

Page 7: JNA

JNI Example (3/3)

#include <windows.h>#include ”HelloJni.h”

JNIEXPORT jint JNICALLJava_HelloJni_msgBox(JNIEnv *env, jobject o, jstring s) {

const char *ns = (*env)->GetStringUTFChars(env,s, NULL);

int i = MessageBoxA(NULL, ns, ”Demo”,MB_ICONINFORMATION);

(*env)->ReleaseStringUTFChars(env, s, ns);return i;

}

7

Page 8: JNA

JNA Example

import com.sun.jna.*;

public class HelloJna {public interface UserLib extends Library {int MB_ICONINFORMATION = 0x40;int MessageBoxA(Pointer p, String s,String t, int type);

}

public static void main(String[] args) {UserLib lib = (UserLib)Native.loadLibrary(”user32”, UserLib.class);

lib.MessageBoxA(null, ”Hello␣World!”, ”Demo”,lib.MB_ICONINFORMATION);

}}

8

Page 9: JNA

Java type mappings

• int→ int32_t• short→ int16_t• long→ int64_t• String→ char*• byte→ char• char→ int16_t

9

Page 10: JNA

JNA mapping classes

• WString→wchar_t*• Pointer→ void*• PlatformLong→ long

10

Page 11: JNA

More features

• Array mapping• Structures• Callbacks• Wrapper generator (JNAerator, third party)

11

Page 12: JNA

Implementation

• Dispatch code implemented using JNI andlibffi

• jna.jar contains platform binaries

12

Page 13: JNA

Alternatives

• BridJ• SWIG

13

Page 14: JNA

Links

• https://github.com/twall/jna• http://en.wikipedia.org/wiki/JNAerator• http://www.swig.org/

14

Page 15: JNA

Questions?

15

Page 16: JNA

Thanks

Twitter @robertbachmann

Email rb@ — .at

16