Writing a Java Program with Native Methods

environment: Ubuntu 16.04.1 LTS (GNU/Linux 4.4.0-31-generic x86_64), JDK 1.8.0_101
  • Hello.java
1
2
3
4
5
6
7
8
9
10
11
public class Hello {
public static native int add(int x, int y);
static{
System.loadLibrary("hello");
}
public static void main(String[] args){
System.out.println(Hello.add(233, 344));
}
}
1
2
$ javac Hello.java
$ javah -jni Hello
  • Hello.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class Hello */
#ifndef _Included_Hello
#define _Included_Hello
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: Hello
* Method: add
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_Hello_add
(JNIEnv *, jclass, jint, jint);
#ifdef __cplusplus
}
#endif
#endif
  • HelloImpl.c
1
2
3
4
5
6
7
8
#include <stdio.h>
#include <jni.h>
#include "Hello.h"
JNIEXPORT jint JNICALL Java_Hello_add
(JNIEnv *env, jclass clazz, jint x, jint y) {
return x + y;
}
1
2
3
$ gcc -shared -I/$JAVA_HOME/include -I/$JAVA_HOME/include/linux -fPIC HelloImpl.c -o libhello.so
$ export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`pwd`
$ java Hello