JNI如何访问Java对象(整数)

新手上路,请多包涵

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

value = 0x4016f3d0

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

请帮忙。

谢谢,

-H

通用对等体.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");
 }
}

数据.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);
      }
}

原文由 user271290 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 726
1 个回答

您必须在 Integer 实例上调用 intValue 方法来获取其原始值。 Use FindClass instead of GetObjectClass (as in your code) to get a reference to the class java.lang.Integer and then GetMethodID and CallObjectMethod 实际调用 intValue 方法。

原文由 jarnbjo 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题