gpt4 book ai didi

c - JNI 二维数组求和

转载 作者:行者123 更新时间:2023-11-30 17:05:47 25 4
gpt4 key购买 nike

想要使用 NDK,我在 android studio 上没有运气(直到现在我还没有得到指示 NDK 路径的意义,因为我在 IDE 之外的终端中执行所有操作并且没有代码完成),我切换到 eclipse这使得使用 jni 和 ndk dev 变得更加容易。

首先,我创建了一个项目来对 c 中的二维整数数组求和并将总和返回到 java 端。我无法让它工作。你能帮忙吗?!!

我的 C 代码是:

 #include <jni.h>
JNIEXPORT jint JNICALL Java_com_example_jninew_MainActivity_getNum(JNIEnv *env, jobject obj, jintArray arr)
{
int i,j, sum = 0;
jsize width = (*env)->GetArrayLength(env, arr);
jintArray *line = (*env)->GetIntArrayElements(env, arr, 0);
for (i=0; i<width; i++){

jint *pos = (*env)->GetIntArrayElements(env, line, i);
for (j=0; j<height; j++){
sum += pos[i][j];
}
}
(*env)->ReleaseIntArrayElements(env, arr, line, 0);
return sum;
}

我的java代码是:

package com.example.jninew;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView) findViewById(R.id.tv);
int[][] a = {{1,2},{3,4}};
textView.setText("sum is: "+getNum(a));


}
static{
System.loadLibrary("getNum");
}
native int getNum(int[][] a);
.
.
.}

最佳答案

我认为应该是这样的:

   #include <jni.h>
JNIEXPORT jint JNICALL Java_com_example_jninew_MainActivity_getNum(JNIEnv *env, jobject obj, jintArray arr)
{
int i,j, sum = 0;
jsize width = (*env)->GetArrayLength(env, arr);

for (i=0; i<width; i++){

jintArray *line = (*env)->GetObjectArrayElement(env, arr, i);
int height = (*env)->GetArrayLength(env, line);
jint *pos = (*env)->GetIntArrayElements(env, line, 0);

for (j=0; j<height; j++){
sum += pos[j];
}
(*env)->ReleaseIntArrayElements(env, arr, pos, 0);
(*env)->ReleaseIntArrayElements(env, arr, line, 0);
}


return sum;
}

关于c - JNI 二维数组求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35090491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com