JNI中使用GetxxxArrayElements来获取具体的某种类型数组,GetObjectArrayElement获取string等类型的对象数组
Test.java
public class Test {
//java给c传递数组
native void test(int[] i,String[] s);
}
MainActivity.java
static {
System.loadLibrary("native-lib");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//传递数组
int[] i = {1,2,3};
String[] j = {"A","B","C"};
Test test = new Test();
test.test(i,j);
}
native-lib
extern "C"
JNIEXPORT void JNICALL
Java_com_example_myapplication_Test_test(JNIEnv *env, jobject instance, jintArray i_,
jobjectArray s) {
/**
* GetIntArrayElements第二个参数:
* true:拷贝一个新数据(新申请内存)
* false:就是使用的java的数组(地址)
*/
jint *i = env->GetIntArrayElements(i_, NULL);//指向数组首元素地址
int32_t length = env->GetArrayLength(i_);
for (int k = 0; k < length ; k++) {
LOGI("获取int数组的数据%d\n",*(i+k));
*(i+k) = 100;
}
env->ReleaseIntArrayElements(i_, i, 0);
/**
* ReleaseIntArrayElements第三个参数:
* 0:刷新java数组,释放c/c++数组
* 1 = JNI_COMMIT:只刷新java数组
* 2 = JNI_ABORT:只释放
*/
jint strlength = env->GetArrayLength(s);
for (int i = 0; i < strlength;i++) {
//static_cast<jstring> 将jobject转为jstring
jstring str = static_cast<jstring>(env->GetObjectArrayElement(s, i));
const char* s = env->GetStringUTFChars(str,0);
LOGI("获取string数组的数据%s\n",s);
env->ReleaseStringUTFChars(str,s);
}
}
网友评论