I have a very simple Java program that takes a double 16 array passes it to a Native C call. In the C function I take each element of the array and sum it up and return that sum. I followed some of the examples online and ran into this where each result returned was 1717986916 not matter what the was in the array. Any ideas what I am doing wrong? Here are my activity and c code.
public class NDKFooActivity extends Activity implements OnClickListener {
// load the library - name matches jni/Android.mk
static {
System.loadLibrary("ndkfoo");
}
// declare the native code function - must match ndkfoo.c
public static native int sumFIR(double[] arr);
private TextView textResult;
private Button buttonGo;
private double[] dList = new double[16];
private List<Double> list = new LinkedList<Double>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textResult = (TextView) findViewById(R.id.textRes开发者_开发知识库ult);
buttonGo = (Button) findViewById(R.id.buttonGo);
buttonGo.setOnClickListener(this);
}
@Override
public void onClick(View view) {
String out = "";
/////////////////////////////////////
//load first 16 data sets
list.add(2135.1); list.add(1130.1); list.add(2530.1); list.add(2430.1);
list.add(2330.1); list.add(1940.1); list.add(1210.1); list.add(2100.1);
list.add(2095.1); list.add(2105.1); list.add(2000.1); list.add(1876.1);
list.add(1852.1); list.add(1776.1); list.add(1726.1); out += "" + add(1716.1);
/////////////////////////////////////
out += "\n" + add(2135.1); out += "\n" + add(1130.1);
out += "\n" + add(2530.1); out += "\n" + add(2430.1);
textResult.setText(out);
}
public double add(double object) {
if (list.size() > 15 ) {
list.remove(0);
}
list.add(object);
for (int i=0; i< 16; i++) {
dList[i] = list.get(i).doubleValue();
}
double dResult = sumFIR(dList);
return dResult;
}
}
ndkfoo.c looks like this:
#include <stdio.h>
#include <stdlib.h>
#include <jni.h>
jdouble Java_com_nsf_ndkfoo_NDKFooActivity_sumFIR (JNIEnv* env, jobject obj, jdoubleArray arr) {
jdouble result = 0;
// initializations, declarations, etc
jint i = 0;
// get a pointer to the array
jdouble *c_array = (*env)->GetDoubleArrayElements(env, arr, 0);
jsize len = (*env)->GetArrayLength(env, arr);
for (i=0; i<16; i++){
result = result + c_array[i];
}
// release the memory so java can have it again
(*env)->ReleaseDoubleArrayElements(env, arr, c_array, 0);
// return something, or not.. it's up to you
return result;
}
Okay found the answer turns out the Java native to the function was using int instead of double. Not sure why it almost always returned the same number.
// declare the native code function - must match ndkfoo.c
public static native int sumFIR(double[] arr);
Should be
public static native double sumFIR(double[] arr);
精彩评论