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


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.


Here is some supplementary sample code to Sergey's answer:

C/C++ side:

JNIEXPORT jint JNICALL Java_com_marakana_NativeLib_add
  (JNIEnv *, jobject, jint, jint);

Java side:

  public native int add( int v1, int v2 );

Source: https://thenewcircle.com/s/post/49/using_ndk_to_call_c_code_from_android_apps

Thanks again to Sergey K., RobinHood and Dharmendra!

链接地址: http://www.djcxy.com/p/61010.html

上一篇: 移动postgresql数据集群

下一篇: Android:从JNI方法获取随机数