标签:android style blog http color io os 使用 java
最近在开发jni时,需要返回多个参数给java。这个过程中,碰到了一些问题,值得探讨一下。
jni_do_something(JNIEnv *env, jobject thiz, jobject p1, jobject p2) { jclass c; jfieldID id; c = env->FindClass("java/lang/Integer"); if (c==NULL) { LOGD("FindClass failed"); return -1; } id = env->GetFieldID(c, "value", "I"); if (id==NULL) { LOGD("GetFiledID failed"); return -1; } env->SetIntField(p1, id, 5); env->SetIntField(p2, id, 10); return 0; }
java层调用如果这样写:
native int do_something(Integer p1, Integer p2); Integer p1=0, p2=0; do_something(p1, p2); Log.d("test", "p1: "+p1); Log.d("test", "p2: "+p2);
这样打印出的值是(10,10),而不是期望的(5,10)。为什么呢?
Integer p1=0, p2=1;
Integer p1 = new Integer(0); Integer p2 = new Integer(0);
/** * Returns a <tt>Integer</tt> instance representing the specified * <tt>int</tt> value. * If a new <tt>Integer</tt> instance is not required, this method * should generally be used in preference to the constructor * {@link #Integer(int)}, as this method is likely to yield * significantly better space and time performance by caching * frequently requested values. * * @param i an <code>int</code> value. * @return a <tt>Integer</tt> instance representing <tt>i</tt>. * @since 1.5 */ public static Integer valueOf(int i) { if (i >= -128 && i <= IntegerCache.high) return IntegerCache.cache[i + 128]; else return new Integer(i); }
回到程序中来,如果写成Integer p0 = 0, p1 = 0,它们是static pool中同一个对象的引用,因此jni中修改的是同一个对象。正确做法应该是使用new。
标签:android style blog http color io os 使用 java
原文地址:http://www.cnblogs.com/CCBB/p/3980856.html