實(shí)現(xiàn)JNI中本地函數(shù)注冊(cè)可以兩種方式: Java端代碼: package com.jni; public class JavaHello { public static native String hello(); static { // load library: libtest.so try { System.loadLibrary("test"); } catch (UnsatisfiedLinkError ule) { System.err.println("WARNING: Could not load library!"); } } public static void main(String[] args) { String s = new JavaHello().hello(); System.out.println(s); } } 本地C語(yǔ)言代碼: #include <stdlib.h> #include <string.h> #include <stdio.h> #include <jni.h> #include <assert.h> JNIEXPORT jstring JNICALL native_hello(JNIEnv *env, jclass clazz) { printf("hello in c native code./n"); return (*env)->NewStringUTF(env, "hello world returned."); } #define JNIREG_CLASS "com/jni/JavaHello"//指定要注冊(cè)的類(lèi) /** * Table of methods associated with a single class. */ static JNINativeMethod gMethods[] = { { "hello", "()Ljava/lang/String;", (void*)native_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, 編譯及運(yùn)行流程: 1 設(shè)置三個(gè)環(huán)境變量: 2 編譯JavaHello.java: 3. 編譯NativeHello.c,生成共享庫(kù) gcc -fPIC -I $JAVA_HOME/include -I $JAVA_HOME/include/linux -shared -o $NATIVE_SRC_PATH/libtest.so $NATIVE_SRC_PATH/NativeHello.o 4. 運(yùn)行 |
|