2

I am facing trouble calling a Java function from C++ method. The following is what I am doing

My java class

package com.q.IT;

public class Carv {

public boolean isValidRatio(float a, float b)
{

       //do something
       return True;
    }
}

My C++ method

void printAndValidateResults() {

    JNIEnv *env;
jclass ItClass =env->FindClass("com/q/IT/Carv");
jobject object = env->AllocObject(ItClass);
jmethodID isValidRatioID = env->GetMethodID(ItClass,"isValidRatio", "(FF)Z");
    bool retVal = env->CallBooleanMethod(object, isValidRatioID, 1.0f,2.0f);
}

I get the following error

06-23 23:35:03.459: A/libc(15758): Fatal signal 11 (SIGSEGV) at 0xe92d43a4 (code=1), thread 16113 (AsyncTask #2)

As you can see, the C++ method is a normal C++ method and not something like

JNIEXPORT void JNICALL Java_com_q_IT_blahblah(JNIEnv *, jobject) {

, I'd like to keep it that way. The crash happens here

jclass ItClass =env->FindClass("com/q/IT/Carv");

I am not quite sure what to initialize *env to.

Harkish
  • 2,262
  • 3
  • 22
  • 31

2 Answers2

3

Your pointer isn't initialized :

JNIEnv *env;
jclass ItClass =env->FindClass("com/q/IT/Carv"); // env has not been set

You have to use the JNIEnv pointer that you get from the JNI call if you want to be able to communicate with your Java code.

Dalmas
  • 26,409
  • 9
  • 67
  • 80
3

As an example, check Creating a JVM from C. It shows a sample procedure to create a JVM and invoke a method. If the JVM already exists; e.g. your C program is invoked by the Java program (callback situation), you can cache the JNIEnv* pointer.

As an advice, be careful caching pointers to the JVM from C/C++, there are some semantics involved as to what you can cache and it could be invoked later on.

Source: How to call Java functions from C++?

Community
  • 1
  • 1
JREN
  • 3,572
  • 3
  • 27
  • 45