英文:
JNI call method of enum throws exception
问题
我在我的Java代码中有以下枚举:
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;
}
}
我需要将它传递给JNI并使用`getCode()`返回的值。为此,我声明了:
public native void initialize(Codec2Mode mode);
以下是我在C++端尝试访问它的方式:
JNIEXPORT void JNICALL Java_jni_Codec2Wrapper_initialize
(JNIEnv *env, jobject, jobject mode) {
jclass enumClass = env->FindClass("jni/Codec2Mode");
jmethodID getCodeMethod = env->GetMethodID(enumClass, "getCode", "()I");
jint value = env->CallIntMethod(mode, getCodeMethod);
std::cout << "Arg = " << value << std::endl;
}
从Java端,我调用codec2.initialize(Codec2Mode.CODEC2_MODE_2400);
。但是我遇到了分段错误。可能出了什么问题?
英文:
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?
答案1
得分: 0
你在这里的签名是不正确的:
jmethodID getCodeMethod = env->GetMethodID(enumClass, "getCode", "(V)I");
应该改为:"()I"
这是你的类中的定义方式。
public int getCode();
descriptor: ()I
你可以像这样获取方法的签名:
> javap -cp . -s -p jni.Codec2Mode
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论