$ cd test_jni
$ cat com/jfo/check.java
package com.jfo;
public class check {
public static native String hello();
static {
try {
System.loadLibrary("test");
} catch (UnsatisfiedLinkError ule) {
System.err.println("WARNING: Could not load library!");
}
}
public static void main(String[] args) {
String s = new check().hello();
System.out.println(s);
}
}
$ javac com/jfo/check.java
$ javah -jni com.jfo.check // this will generate "com_jfo_check.h" header file.
$ ls
com com_jfo_check.h jni
// 对com_jfo_check.h 修改,主要是对函数名字改回原来的名称,去除了package+classname前缀
$ cat com_jfo_check.h
/ DO NOT EDIT THIS FILE - it is machine generated /
#include <jni.h>
/ Header for class com_jfo_check /
#ifndef _Included_com_jfo_check
#define _Included_com_jfo_check
#ifdef cplusplus
extern "C" {
#endif
/
Class: com_jfo_check
Method: hello
Signature: ()Ljava/lang/String;
/
JNIEXPORT jstring JNICALL hello(JNIEnv , jclass);
#ifdef cplusplus
}
#endif
#endif
$ mv com_jfo_check.h jni/
$ cat jni/test.c
#include <stdio.h>
#include <stdlib.h>
#include "com_jfo_check.h"
JNIEXPORT jstring JNICALL hello(JNIEnv env, jclass clazz)
{
printf("hello in cpp.n");
return (env)->NewStringUTF(env, "hello world returned.");
}
$ cat jni/jni_reg.c
#include <string.h>
#include <stdio.h>
#include <jni.h>
#include <assert.h>
#include "com_jfo_check.h"
#define JNIREG_CLASS "com/jfo/check"
/
Table of methods associated with a single class.
/
static JNINativeMethod gMethods[] = {
{ "hello", "()Ljava/lang/String;", (void)hello },
};
/
Register several native methods for one class.
/
static int registerNativeMethods(JNIEnv env, const char className,
JNINativeMethod gMethods, int numMethods)
{
jclass clazz;
clazz = (env)->FindClass(env, className);
if (clazz == NULL) {
return JNI_FALSE;
}
if ((env)->RegisterNatives(env, clazz, gMethods, numMethods) < 0) {
return JNI_FALSE;
}
return JNI_TRUE;
}
/
Register native methods for all classes we know about.
/
static int registerNatives(JNIEnv env)
{
if (!registerNativeMethods(env,
JNIREG_CLASS,
gMethods, sizeof(gMethods) / sizeof(gMethods[0])))
return JNI_FALSE;
return JNI_TRUE;
}
/
Set some test stuff up.
Returns the JNI version on success, -1 on failure.
/
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM vm, void reserved)
{
JNIEnv env = NULL;
jint result = -1;
if ((vm)->GetEnv(vm, (void) &env, JNI_VERSION_1_4) != JNI_OK) {
return -1;
}
assert(env != NULL);
if (!registerNatives(env)) {
return -1;
}
/ success – return valid version number /
result = JNI_VERSION_1_4;
return result;
}
$ cd jni
$ gcc -I $JAVA_HOME/include -I $JAVA_HOME/include/linux -c test.c
$ gcc -I $JAVA_HOME/include -I $JAVA_HOME/include/linux -c jni_reg.c
$ gcc -nostdlib -Wl,-soname,libtest.so -Wl,-shared test.o jni_reg.o -o libtest.so
$ cd ../
$ java -Djava.library.path=jni com/jfo/check
hello in cpp.
hello world returned.end