1. 进程间的通信方式有哪些
2. binder 和 socket 通信的区别有哪些
3. Android 为什么在大部分场景下用 Binder 进行进程间通信
4. Serializable 和 Parcelable 之间的区别
5. Parcelable 序列化和反序列化的具体过程
不知道大家在面试中的过程中,有没有碰到上面类似的问题,我在腾讯和 oppo 面试的时候就碰到了,这些问题可能都比较简单。比如:Serializable 开销大,Parcelable 更加高效,但是若要问为什么是这样?恐怕就会有一小部分人答不上来了。今天我们就带大家来了解这些知识,既然学了一些 JNI 基础,那么我们自己从 native 层来实现这些。
之前讲 opencv 有说到,可以用纯 java 代码去写,在 opencv 中 native 层操作的是 Mat 数据矩阵,对应 java 层也有 Mat 这个类,我们看下 java 和 native 是怎么对应起来的。
1// C++: class Mat 2//javadoc: Mat 3public class Mat { 4 5 public final long nativeObj; 6 7 public Mat(long addr) 8 { 9 if (addr == 0) 10 throw new java.lang.UnsupportedOperationException("Native object address is NULL"); 11 nativeObj = addr; 12 } 13 14 // 15 // C++: Mat::Mat() 16 // 17 // javadoc: Mat::Mat() 18 public Mat() 19 { 20 nativeObj = n_Mat(); 21 return; 22 } 23 24 // 25 // C++: Mat::Mat(int rows, int cols, int type) 26 // 27 // javadoc: Mat::Mat(rows, cols, type) 28 public Mat(int rows, int cols, int type) 29 { 30 // 在 c++ 层创建一个对象,然后把指针地址 jlong 返回给 java 层 31 nativeObj = n_Mat(rows, cols, type); 32 return; 33 } 34 35 // C++: Mat::Mat() 36 private static native long n_Mat(); 37 38 // C++: Mat::Mat(int rows, int cols, int type) 39 private static native long n_Mat(int rows, int cols, int type); 40}
1JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1Mat__DDI 2 (JNIEnv* env, jclass, jdouble size_width, jdouble size_height, jint type) 3{ 4 static const char method_name[] = "Mat::n_1Mat__DDI()"; 5 try { 6 LOGD("%s", method_name); 7 Size size((int)size_width, (int)size_height); 8 return (jlong) new Mat( size, type ); 9 } catch(const std::exception &e) { 10 throwJavaException(env, &e, method_name); 11 } catch (...) { 12 throwJavaException(env, 0, method_name); 13 } 14 15 return 0; 16}
上面的代码比较简单,当我们调用 Mat mat = new Mat(720,1280,CvType.CV_8UC4) ,这个时候会调用 native 层去创建 c++ 的 Mat 对象,然后将指针地址回调给 java 层,为什么要这么做?其实我们也能猜到,c++ 操作的是 native 层的 Mat 的对象,我们把创建好的对象指针给 java 层,是为了再次在 native 层操作的时候,可以根据指针地址找到对应 c++ 的 Mat 对象,然后就可以进行一些列的操作。
为什么讲到 opencv 去了?其实这次的重点就是,在 JNI 的开发过程中,native 层的对象怎么传给 java 层的对象进行保存和操作。接下来我们再来看一个例子 Android 共享内存的序列化过程,相信只要看过 Parcel 的源码,上面的所有问题都迎刃而解了。如果没有 frameworker 层的源码,请先去下载,千万不要下载阉割版的,里面要有 native 层的源码。
1public final class Parcel { 2 // 保存的是 c++ 层的 Parcel.cpp 对象的指针地址 3 private long mNativePtr; // used by native code 4 5 private Parcel(long nativePtr) { 6 if (DEBUG_RECYCLE) { 7 mStack = new RuntimeException(); 8 } 9 //Log.i(TAG, "Initializing obj=0x" + Integer.toHexString(obj), mStack); 10 init(nativePtr); 11 } 12 13 private void init(long nativePtr) { 14 if (nativePtr != 0) { 15 mNativePtr = nativePtr; 16 mOwnsNativeParcelObject = false; 17 } else { 18 mNativePtr = nativeCreate(); 19 mOwnsNativeParcelObject = true; 20 } 21 } 22 23 /** 24 * Write an integer value into the parcel at the current dataPosition(), 25 * growing dataCapacity() if needed. 26 */ 27 public final void writeInt(int val) { 28 nativeWriteInt(mNativePtr, val); 29 } 30 31 /** 32 * Read an integer value from the parcel at the current dataPosition(). 33 */ 34 public final int readInt() { 35 return nativeReadInt(mNativePtr); 36 } 37 // 创建 Parcel.cpp 返回 jlong 38 private static native long nativeCreate(); 39 // 写入 int 数据 40 private static native void nativeWriteInt(long nativePtr, int val); 41 // 读 int 数据 42 private static native int nativeReadInt(long nativePtr); 43}
1// 创建 Parcel ,返回指针地址给 java 层 2static jlong android_os_Parcel_create(JNIEnv* env, jclass clazz) 3{ 4 Parcel* parcel = new Parcel(); 5 return reinterpret_cast<jlong>(parcel); 6} 7// 通过指针地址获取 c++ 层的对象,然后进行操作 8static void android_os_Parcel_writeInt(JNIEnv* env, jclass clazz, jlong nativePtr, jint val) { 9 Parcel* parcel = reinterpret_cast<Parcel*>(nativePtr); 10 if (parcel != NULL) { 11 const status_t err = parcel->writeInt32(val); 12 if (err != NO_ERROR) { 13 signalExceptionForError(env, clazz, err); 14 } 15 } 16}
1status_t Parcel::writeInt32(int32_t val) 2{ 3 return writeAligned(val); 4} 5 6template<class T> 7status_t Parcel::writeAligned(T val) { 8 COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE_UNSAFE(sizeof(T)) == sizeof(T)); 9 // 判断大小有没有超过 10 if ((mDataPos+sizeof(val)) <= mDataCapacity) { 11restart_write: 12 // 往内存上写入数据 13 *reinterpret_cast<T*>(mData+mDataPos) = val; 14 // 返回写入成功 15 return finishWrite(sizeof(val)); 16 } 17 // 返回错误 18 status_t err = growData(sizeof(val)); 19 if (err == NO_ERROR) goto restart_write; 20 return err; 21} 22 23int32_t Parcel::readInt32() const 24{ 25 return readAligned<int32_t>(); 26} 27 28template<class T> 29T Parcel::readAligned() const { 30 T result; 31 if (readAligned(&result) != NO_ERROR) { 32 result = 0; 33 } 34 return result; 35} 36 37template<class T> 38status_t Parcel::readAligned(T *pArg) const { 39 COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE_UNSAFE(sizeof(T)) == sizeof(T)); 40 // 有没有超出 41 if ((mDataPos+sizeof(T)) <= mDataSize) { 42 // 去除当前内存上的值 43 const void* data = mData+mDataPos; 44 // 当前累加往后逻动 45 mDataPos += sizeof(T); 46 // 取出来并赋值 47 *pArg = *reinterpret_cast<const T*>(data); 48 return NO_ERROR; 49 } else { 50 return NOT_ENOUGH_DATA; 51 } 52}
看到这里再来说共享内存,或者说 binder 驱动就会变得简单起来了,Parcel 其实就是在 native 层开辟了一块内存,然后按照一定的顺序往这块内存里面写数据。当我需要取数据的时候,我们按照原来写的顺序取出来就可以了。写的顺序和取的顺序必须保持一致,不然肯定会出错。那为什么不在 java 层做呢?请问在 java 层能做到这些效果吗?这也证实了其实 c 和 c++ 更加灵活,因为操作的是一块内存地址上的数据,想干嘛就可以干嘛。怎么回答上面的问题应该不用我说了,了解了原理那么在回答的时候可以自己做一些扩展。
既然是 JNI 基础部分,那么我们最好还是自己动手来敲一下。好比要了解 Retrofit 、OkHttp 和 RxJava 这些常用开源库,我们最好自己动手敲一下核心部分,就能更加加深印象。
1 var parcel = Parcel.obtain() 2 3 parcel.writeInt(12) 4 parcel.writeInt(24) 5 6 var number1 = parcel.readInt() 7 var number2 = parcel.readInt() 8 9 Log.e("TAG","number1 = $number1 , number2 = $number2")
1class Parcel{ 2 private var mNativePtr: Long = 0 // used by native code 3 init { 4 System.loadLibrary("native-lib") 5 mNativePtr = nativeCreate(); 6 } 7 private external fun nativeCreate(): Long; 8 9 // 两个读写 int 的方法 10 fun writeInt(value: Int) { 11 nativeWriteInt(mNativePtr, value); 12 } 13 fun readInt(): Any { 14 return nativeReadInt(mNativePtr) 15 } 16 // 两个读写 native 方法 17 private external fun nativeWriteInt(mNativePtr: Long, value: Int); 18 private external fun nativeReadInt(nativePtr: Long): Int 19}
视频地址:https://pan.baidu.com/s/1H2d3mxxZJn7brGEYKNrCHw 视频密码:i81c
本文转自 https://juejin.cn/post/6844903608324997128,如有侵权,请联系删除。
