JNI如何访问Java Object(Integer)

时间:2010-04-13 14:53:01

标签: java c++ java-native-interface

我有一个JNI方法来访问返回Integer对象的java方法。我不想返回原始int类型,因为将修改此代码以处理Generic对象。以下是我所拥有的。我无法获得通过的Integer的值。 C ++端的输出类似于

value = 0x4016f3d0

如何获取我在C ++端传递的Integer对象的实际值?

请帮忙。

谢谢,

-H

GenericPeer.cpp

JNIEXPORT void JNICALL Java_GenericPeer_print (JNIEnv *jenv, jclass jcls, jobject data){
 jclass peerCls = jenv->GetObjectClass(data);
 jmethodID mGetValue = jenv->GetMethodID(peerCls, "getValue","()Ljava/lang/Integer;");
 if(mGetValue == NULL){
   return (-1);
 } 
 jobject value = jenv->CallObjectMethod(data, mGetValue);
 cout<<"value = "<<value<<endl;

}

GenericPeer.java

public class GenericPeer {
 public static native void print(Data d);
 static {
  System.load("/home/usr/workspace/GenericJni/src/libGenericJni.so");
 }
}

Data.java

public class Data {
 private Integer value;
 pubilc Data(Integer v){ 
  this.value = v;
 }
 public Integer getValue() { return value; }
    public void setValue(Integer value) {
 this.value = value;
 }
}

Test.java(主类)

public class Test {
 public static void main(String[] args){
       Integer i = new Integer(1);
  Data d = new Data(i);
  GenericPeer.print(d);
      }
}

2 个答案:

答案 0 :(得分:11)

您必须在Integer实例上调用intValue方法以获取其原始值。使用FindClass代替GetObjectClass(如代码中所示)来获取对类java.lang.Integer的引用,然后GetMethodIDCallObjectMethod来实际调用{{ 1}}方法。

答案 1 :(得分:9)

谢谢Jarnbjo,

现在有效!这就是我所拥有的:

    JNIEXPORT jint JNICALL Java_GenericPeer_print (JNIEnv *jenv, jclass jcls, jobject data){
      jclass peerCls = jenv->GetObjectClass(data);

     jmethodID mGetValue = jenv->GetMethodID(peerCls, "getValue","()Ljava/lang/Integer;");
     if (mGetValue == NULL){
       return(-1);
     }

     jobject value = jenv->CallObjectMethod(data, mGetValue);
     if(value == NULL){
      cout<<"jobject value = NULL"<<endl;
      return(-1);
     }

    //getValue()

     jclass cls = jenv->FindClass("java/lang/Integer");
     if(cls == NULL){
       outFile<<"cannot find FindClass(java/lang/Integer)"<<endl;
     }
       jmethodID getVal = jenv->GetMethodID(cls, "intValue", "()I");
       if(getVal == NULL){
         outFile<<"Couldnot find Int getValue()"<<endl;
       }
       int i = jenv->CallIntMethod(value, getVal);
}   
相关问题