Search code examples
javajava-native-interface

JNI call method of enum throws exception


I have the following enum inside my java code :

package jni;

public enum Codec2Mode {
    CODEC2_MODE_3200(0),
    CODEC2_MODE_2400(1),
    CODEC2_MODE_1600(2),
    CODEC2_MODE_1400(3),
    CODEC2_MODE_1300(4),
    CODEC2_MODE_1200(5),
    CODEC2_MODE_700C(8),
    CODEC2_MODE_450(10),
    CODEC2_MODE_450PWB(11);

    private int m_code;

    public int getCode()
    {
        return m_code;
    }

    Codec2Mode( int code )
    {
        m_code = code;
    }
}

I need to pass it to JNI and use a value returned by getCode(). For this I declare

public native void initialize(Codec2Mode mode);

And here is the way I'm trying to access it at C++ side :

JNIEXPORT void JNICALL Java_jni_Codec2Wrapper_initialize
  (JNIEnv * env, jobject, jobject mode)
{
   jclass enumClass = env->FindClass("jni/Codec2Mode");

   jmethodID getCodeMethod = env->GetMethodID(enumClass, "getCode", "(V)I");

   jint value = env->CallIntMethod(mode, getCodeMethod);

   std::cout << "Arg = " << value << std::endl;
}

From java I call codec2.initialize(Codec2Mode.CODEC2_MODE_2400);. But I get segmentation fault. What's could be an issue here?


Solution

  • You have incorrect signature here:

    jmethodID getCodeMethod = env->GetMethodID(enumClass, "getCode", "(V)I");
    

    It should read: "()I"

    It's how it is defined in your class.

    public int getCode();
        descriptor: ()I
    

    you can get signature of the method like that

    > javap -cp . -s -p jni.Codec2Mode