没有逐字翻译,解说了文章的大体意思,须要了解细节的请看原文~html
有时候咱们须要Native code(c/c++)来克服Java中的内存管理和性能约束。 Java经过JVM提供的JNI功能达到了这个目的。JNI涉及到两种语言和运行时环境,因此比较难点。这里我假设你对Java,c/c++,相关IDE比较熟悉。java
2.1 在Java中使用C: c++
2.2 在Java中混合c/c++数组
主要问题是,要明白如何在c源文件中调用c++函数(函数声明的时候要注意使用extern “C")app
2.3 JNI相关的包问题ide
若是包含native方法的类不是在默认包里,就涉及到这个问题,在使用javah的时候须要注意切换到package base directory。函数
2.4 JNI在Eclipse中的使用 工具
4.1 传递原始类型(primitives)性能
4.2 传递字符串spa
// UTF-8 String (encoded to 1-3 byte, backward compatible with 7-bit ASCII) // Can be mapped to null-terminated char-array C-string const char * GetStringUTFChars(JNIEnv *env, jstring string, jboolean *isCopy); // 返回jstring对象中的内部c字符串 void ReleaseStringUTFChars(JNIEnv *env, jstring string, const char *utf); // 告诉虚拟机native code再也不须要访问jstring的utf jstring NewStringUTF(JNIEnv *env, const char *bytes); //新建立一个java.lang.String 对象 jsize GetStringUTFLength(JNIEnv *env, jstring string); // Returns the length in bytes of the modified UTF-8 representation of a string. void GetStringUTFRegion(JNIEnv *env, jstring str, jsize start, jsize length, char *buf); // Translates len number of Unicode characters beginning at offset start into modified UTF-8 encoding // and place the result in the given buffer buf
4.3 传递原始类型的数组
(如何在native code中修改Java对象的值)
5.1 实例变量
5.2 类的静态变量
5.3 方法调用
5.4 调用overridden的方法
1 classInteger = (*env)->FindClass(env, "java/lang/Integer"); //这里得到是Local 引用,即便保存的全局变量里,下次也不能使用,因此须要从新申请,或者像下面这样: 2 3 // Get a class reference for java.lang.Integer if missing 4 if (NULL == classInteger) { 5 printf("Find java.lang.Integer\n"); 6 // FindClass returns a local reference 7 jclass classIntegerLocal = (*env)->FindClass(env, "java/lang/Integer"); 8 // Create a global reference from the local reference 9 classInteger = (*env)->NewGlobalRef(env, classIntegerLocal); 10 // No longer need the local reference, free it! 11 (*env)->DeleteLocalRef(env, classIntegerLocal); 12 }
原文连接: https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html