2011-10-04 116 views
0

我有一个非常简单的Java程序,它将一个双16数组传递给本机C调用。在C函数中,我获取数组的每个元素并对其进行求和并返回该和。我在网上跟踪了一些示例,并且遇到了这种情况,每个返回的结果都是1717986916,不管数组中的内容如何。任何想法我做错了什么?这里是我的活动和C代码。来自本机调用的结果总是返回1717986916

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.textResult); 
     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看起来是这样的:

#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; 
} 

回答

0

奥凯找到答案了原来的Java本机的功能是使用int,而不是双。不知道为什么它几乎总是返回相同的数字。

// declare the native code function - must match ndkfoo.c 
public static native int sumFIR(double[] arr); 

应该

public static native double sumFIR(double[] arr); 
相关问题