Android: getting random number from JNI method

I am creating a demo of a mathematical operation such as addition, subtraction, multiplication and division using the NDK.

I can make a library and get a response from my own code, but the result is not correct, I mean that this is a random static value.

Class Calculator.c

#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 to load the library and run your own 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 use the code below to display the 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))); 

Exit

enter image description here

+7
source share
2 answers

You declare non-static methods and do not pass a reference to "jobject" - that is why you get garbage in the return value.

To fix the error, you must add an additional argument for "jobject" in the native code immediately after the argument "env".

+4
source

Here is another example code to answer Sergey:

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!

0
source

All Articles