MainActivity
package com.example.arraydeliver;Native.c
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.os.Build;
public class MainActivity extends Activity {
byte[] a=new byte[]{0x32,0x33,0x34,'\0'};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv= new TextView(this);
tv.setText(stringFromJNI(a));
setContentView(tv);
}
public native static String stringFromJNI(byte[] a);
static {
System.loadLibrary("hello-jni");
}
}
#include <string.h>
#include <jni.h>
#include <stdlib.h>
typedef unsigned char byte;
JNIEXPORT jstring JNICALL Java_com_example_arraydeliver_MainActivity_stringFromJNI( JNIEnv* env,jobject thiz ,jbyteArray j){
jbyte *temp=(*env)->GetByteArrayElements(env,j,0);
char *x=(char *)temp;
return (*env)->NewStringUTF(env,x+sizeof(x));
}
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := hello-jni
LOCAL_SRC_FILES := Native.c
include $(BUILD_SHARED_LIBRARY)
注意:在Native.c中的 GetByteArrayElements其实是获取java中的数组指针,所以在使用完后记得要释放(*env)->ReleaseByteArrayElements(env,j,temp,0)
注意2:C和C++中有些参数略有不同:C++中直接传入env->引用,C中则需要(×env)->,在C中 jbyte *temp=(*env)->GetByteArrayElements(env,j,0);
而在C++中则 jbyte *temp=env->GetByteArrayElements(j,0);