要实现在java 端传递bytearray 到jni 端,同时在jni 端要反馈回bytearray
在java 端的声明如下:
public native byte[] Bluetooth_NativeProcessData_Send(byte[] data,int len);public native byte[] Bluetooth_NativeProcessData_Receive(byte[] data,int len);
如下是jni 端的声明
static JNINativeMethod gMethods[] = {{"Bluetooth_NativeProcessData_Send","([BI)[B",(void*)Native_ProcessData_Send},{"Bluetooth_NativeProcessData_Receive","([BI)[B",(void*)Native_ProcessData_Receive},};
在jni 端的实现:
jbyte gs_raw_data[256];jbyte gr_raw_data[256];
JNIEXPORT jbyteArray JNICALL Native_ProcessData_Send(JNIEnv *env, jobject clazz, jbyteArray data,jint len){
jclass cls; int i; cls = env->FindClass(JNIREG_CLASS); jbyte* bytedata =env->GetByteArrayElements(data, 0);
memset(&gs_raw_data,0,255); memcpy(&gs_raw_data,bytedata,len);
// parse the data //below is the return ‘s bytearray lens
jbyteArray jarrRV =env->NewByteArray(len+1);
env->SetByteArrayRegion(jarrRV, 0,len,gs_raw_data);
return jarrRV;}
JNIEXPORT jbyteArray JNICALL Native_ProcessData_Receive(JNIEnv *env, jobject clazz, jbyteArray data,jint len){jclass cls; int i; cls = env->FindClass(JNIREG_CLASS); jbyte* bytedata =env->GetByteArrayElements(data, 0);
memset(&gr_raw_data,0,255); memcpy(&gr_raw_data,bytedata,len); // parse the data and process your data //try to process the data for(i=0;i<len;i++) { gr_raw_data[i]=bytedata[i]+1; } //after proces the data, you can return the processed data lens which may be different the raw len // note below is the return ‘s bytearray lens jbyteArray jarrRV =env->NewByteArray(len+1);
env->SetByteArrayRegion(jarrRV, 0,len,gs_raw_data);
return jarrRV;}
//blow is the java to call jni and pass the byte array to jni and return from jni
public void test(t) { // Create temporary object int ilength,i; byte[] retdata; byte[] out1 = new byte[1024]; { out1[0] =(byte) 0X31; out1[1] =(byte) 0X32; out1[2] =0x33; out1[3] =0x34; out1[4] = 0x35; } retdata=Bluetooth_NativeProcessData_Send(out1,5); { Log.d(TAG,"THE rawdata IS—"+bytesToHex(out1,5)); Log.d(TAG,"THE RETDATA IS—"+bytesToHex(retdata,5)); }
人若软弱就是自己最大的敌人