Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Getting random number from JNI method

I am creating a demo of math operation like addition, subtraction, multiplication and division using NDK.

I am able to make the library and getting the response from the native code but result is not proper I mean it is random static value.

Calculator.c class

#include <stdio.h>
#include <jni.h>

jint
Java_com_example_jni_calculator_Calculator_add(JNIEnv* env, jint a, jint b) {
    return (jint)(a + b);
}

jint
Java_com_example_jni_calculator_Calculator_substract(JNIEnv* env, jint a, jint b) {
    return (jint)(a - b);
}

jint
Java_com_example_jni_calculator_Calculator_multiply(JNIEnv* env, jint a, jint b) {
    return (jint)(a * b);
}

jint
Java_com_example_jni_calculator_Calculator_devide(JNIEnv* env, jint a, jint b) {
    return (jint)(a / b);
}

Calculator.java class for load library and initiating native methods.

public class Calculator {

    static {
        System.loadLibrary("Calculator");
    }

    public native int add(int a, int b);
    public native int substract(int a, int b);
    public native int multiply(int a, int b);
    public native int devide(int a, int b);
}

I am using below code to display result:

int num1 = Integer.parseInt(txtNumber1.getText().toString().trim());
int num2 = Integer.parseInt(txtNumber2.getText().toString().trim());
tvResult.setText(String.format("%1$d + %2$d is equals to %3$d", num1, num2, mCalculator.add(num1, num2)));

Output

enter image description here

like image 932
Dharmendra Avatar asked Jun 30 '12 06:06

Dharmendra


1 Answers

You are declaring non-static methods and don't pass a reference to "jobject" - that is why you are getting garbage in the return value.

To fix the bug you have to add an extra argument for "jobject" in the native code, just after the "env"argument.

like image 115
Sergey K. Avatar answered Sep 18 '22 00:09

Sergey K.