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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With