Zax
Zax

Reputation: 3010

Error calling java function from native code

I want to call a java method from native code. I followed the steps given in: Calling a java method from c++ in Android

However my application crashes at the place where the java function is called.

My java code is as shown below:

package com.example.jnitry;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.d("MYAPP","Ocreate entered....");
        Button btn=(Button) findViewById(R.id.button1);
        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                mainfunc(8);
            }
        });
    }

    public void display(byte[] byt){
        Log.d("MYAPP", "display() is entered....");
        for(int i=0;i<byt.length;i++)
            Log.d("MYAPP", "byt["+i+"]="+byt[i]);
        Log.d("MYAPP", "display finished");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    public static native void mainfunc(int n);

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

My native code is as shown below:

#include <jni.h>
#include "com_example_jnitry_MainActivity.h"
#include <android/log.h>
#include <stdio.h>

JNIEXPORT void JNICALL Java_com_example_jnitry_MainActivity_mainfunc
  (JNIEnv *env, jclass obj, jint n){

    __android_log_print(ANDROID_LOG_DEBUG,"MYAPP","mainfunction entered...",NULL);
    int i;
    unsigned char arr[10];
    jbyteArray bArray=(*env)->NewByteArray(env,n);

    jclass cls = (*env)->FindClass(env, "com/example/jnitry/MainActivity");
        jmethodID mid = (*env)->GetMethodID(env, cls, "display", "([B)V");
        if (mid == 0){
            __android_log_print(ANDROID_LOG_DEBUG,"MYAPP","mid==0",NULL);
            return;
        }
        if(bArray==NULL)
            {   __android_log_print(ANDROID_LOG_DEBUG,"MYAPP","bArray==NULL...",NULL);
                return ;
            }
    for(i=0;i<n;i++){
        arr[i]=i;
        __android_log_print(ANDROID_LOG_DEBUG,"MYAPP","Iteration number:%d",i);
    }

    (*env)->SetByteArrayRegion(env,bArray,0,n,arr);
    __android_log_print(ANDROID_LOG_DEBUG,"MYAPP","bArray successfully created...",NULL);
    (*env)->CallVoidMethod(env, obj, mid, bArray);
    __android_log_print(ANDROID_LOG_DEBUG,"MYAPP","Returned from disp() java function.....",NULL);

}

My app crashes after printing the log message:

02-14 15:37:06.814: D/MYAPP(11584): bArray successfully created...

Can anyone please tell me the reason. And provide a solution for the same. Thanks in advance.

Note: I have already tried CallVoidMedthodA(), callByteMethod(), CallObjectMethod() but they outcome was the same.

Upvotes: 0

Views: 1499

Answers (3)

Seva Alekseyev
Seva Alekseyev

Reputation: 61396

Your native method mainFunc is a static method - it does not have a valid this pointer. Meanwhile, display is an instance method - it needs one.

The second parameter of mainFunc is actually a class object pointer for MainActivity, as per JNI rules. Declare mainFunc as nonstatic on Java side, and this will work.

Upvotes: 3

18446744073709551615
18446744073709551615

Reputation: 16872

I can give you this. It works. But it is C++. (SO ate the tabs -- sorry.)

// it returns NULL in the case of an exception
// the returned memory is calloc()'d; it's the caller's responsibility to free() it.
char* changeEncoding(const char*source, int len, int direction)
{
    JNIEnv* env = threadUnsafeInfo.env;
    jobject obj = threadUnsafeInfo.obj;

    if (!source) {
    JNU_ThrowByName(env, "java/lang/NullPointerException", 0);
    return NULL;
    }
    jbyteArray srcArray = env->NewByteArray(len);

    jclass cls = env->FindClass("com/xxx/Yyy");
    jmethodID mid = env->GetMethodID(cls, "convert", "([BI)[B");

    if (mid != NULL && srcArray != NULL) {
    env->SetByteArrayRegion(srcArray, 0, len, (jbyte*)source);
    env->ExceptionClear();

    jbyteArray resArray = (jbyteArray)env->CallObjectMethod(obj, mid, srcArray, direction);
    if(env->ExceptionOccurred()) {
        DLOG("exception in convert ([BI)[B");
        env->ExceptionDescribe();
        //env->ExceptionClear(); // ??
        return NULL;
    }

    int resultLen = env->GetArrayLength(resArray);
    char* result = (char*)calloc(2 + resultLen,1); // why 2: a bit of healthy paranoia ain't gonna hurt anyone
    if (result == 0) {
        JNU_ThrowByName(env, "java/lang/OutOfMemoryError", 0);
        return NULL;
    }
    env->GetByteArrayRegion(resArray, 0, resultLen, (jbyte *)result);
    env->DeleteLocalRef(cls);
    env->DeleteLocalRef(resArray);
    env->DeleteLocalRef(srcArray);
    return result;
    } else {
    JNU_ThrowByName(env, "java/lang/NullPointerException", 0);
    myassert(("method id = 0",0));
    }
    return NULL;
}

Upvotes: 1

18446744073709551615
18446744073709551615

Reputation: 16872

AFAIK CallVoidMethod does not take the env argument. At least in C++.

Upvotes: 0

Related Questions