Java 代码:
package com.fansen.hellojni; import android.annotation.SuppressLint; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.widget.TextView; public class MainActivity extends Activity { @SuppressLint("DefaultLocale") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = new TextView(this); tv.setText( "Hello World!" ); String str = null; DiskInfo[] infos = stringFromJNI(); for (int i = 0; i < infos.length; i++) { String aByte = null; if (Integer.toHexString(infos[i].value).toUpperCase().length() == 1) { aByte = "0" + Integer.toHexString(infos[i].value).toUpperCase(); Log.i("TAG", "infos[" + i + "].value: " + "0" + Integer.toHexString(infos[i].value).toUpperCase()); }else { aByte = Integer.toHexString(infos[i].value).toUpperCase(); Log.i("TAG", "infos[" + i + "].value: " + Integer.toHexString(infos[i].value).toUpperCase()); } if (str == null) { str = aByte; }else { str = str + aByte; } } Log.i("TAG", "str: " + str); setContentView(tv); } public native DiskInfo[] stringFromJNI(); static { System.loadLibrary("hello-jni"); } } class DiskInfo{ public int data; public int value; public int number; }
C代码:
#include <string.h> #include <jni.h> typedef struct{ int data; int value; int number; } DiskInfo; jobjectArray Java_com_fansen_hellojni_MainActivity_stringFromJNI( JNIEnv* env, jobject thiz ) { jclass clsDiskInfo = (*env)->FindClass(env, "com/fansen/hellojni/DiskInfo"); jobjectArray infos = (*env)->NewObjectArray(env, 10, clsDiskInfo, NULL); jfieldID dataID = (*env)->GetFieldID(env, clsDiskInfo, "data", "I"); jfieldID valueID = (*env)->GetFieldID(env, clsDiskInfo, "value", "I"); jfieldID numberID = (*env)->GetFieldID(env, clsDiskInfo, "number", "I"); jmethodID consID = (*env)->GetMethodID(env, clsDiskInfo, "<init>", "()V"); unsigned char send[10] = {0xFF,0x1F,0x07,0x08,0x00,0x00,0x01,0x02}; int sendcopy[10] = {0}; int j; for(j = 0; j <= 8; j++){ sendcopy[j] = send[j]; } int i; jobject obj; for(i = 0; i < 10; i++){ obj = (*env)->NewObject(env, clsDiskInfo, consID); (*env)->SetIntField(env, obj, dataID, (jint)i); (*env)->SetIntField(env, obj, valueID, (jint)sendcopy[i]); (*env)->SetIntField(env, obj, numberID, (jint)i); (*env)->SetObjectArrayElement(env, infos, i, obj); } return infos; }
时间: 2024-11-08 21:57:09