使用ndk android的两个值的总和

Man*_*aya 3 java-native-interface android android-ndk

我已成功运行我的jni sample.Now我正在尝试添加两个值,但它的总和不合适.我正在分享我的代码.请告诉我我在做什么错

 jint Java_com_example_hellojni_HelloJni_sumTwoValues( JNIEnv* env,jint a, jint b){
//_android_log_print("HelloJni", "values a", "%p", &a);

    __android_log_print("HelloJni", "LOG_TAG", "Need to print : %d %d",a, b);
    return (a+b);
 }
Run Code Online (Sandbox Code Playgroud)

我如何从我的活动中调用这个方法如下.

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    /* Create a TextView and set its content.
     * the text is retrieved by calling a native
     * function.
     */
    TextView  tv = new TextView(this);
    tv.setText("Sum is ."+ sumTwoValues(15,7));
    setContentView(tv);
}



/* A native method that is implemented by the
 * 'hellojni' native library, which is packaged
 * with this application.
 */

public native int sumTwoValues(int a,int b);


// Loading 'hellojni' 

static {
    System.loadLibrary("hellojni");
}
Run Code Online (Sandbox Code Playgroud)

Textview的文本并不固定.每次运行时都不同.我的总和是363855916

Ami*_*pta 6

试试吧

jint Java_com_example_hellojni_HelloJni_sumTwoValues( JNIEnv* env, jobject obj,jint a, jint b){
//_android_log_print("HelloJni", "values a", "%p", &a);

    __android_log_print("HelloJni", "LOG_TAG", "Need to print : %d %d",a, b);
    return (a+b);
 }
Run Code Online (Sandbox Code Playgroud)

B'coz你定义

public native int sumTwoValues(int a,int b); 非静态的

而如果

public native static int sumTwoValues(int a,int b); static method
Run Code Online (Sandbox Code Playgroud)

然后使用jclass而不是jobject