JNI如何访问Java Object(Integer) [英] JNI how to access Java Object (Integer)
问题描述
我有一个JNI方法来访问返回Integer对象的java方法。我不想返回原始int类型,因为将修改此代码以处理Generic对象。以下是我所拥有的。我无法获得通过的Integer的值。 C ++方面的输出类似于
I have a JNI method to access java method which returns an Integer object. I do not want to return the primitive int type because this code will be modified to handle Generic objects. The following is what I have. I am not able to get the value of the Integer that I pass. The output at C++ side is something like
value = 0x4016f3d0
如何获得我在C ++端传递的Integer对象的实际值?
How can I get the actual value of Integer object that I pass at C++ end?
请帮忙。
谢谢,
-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);
}
}
推荐答案
你必须在Integer实例上调用 intValue
方法以获取其原始值。使用 FindClass
而不是 GetObjectClass
(如在您的代码中)获取对java.lang.Integer类的引用然后 GetMethodID
和 CallObjectMethod
实际调用 intValue
方法。
You have to invoke the intValue
method on the Integer instance to get its primitive value. Use FindClass
instead of GetObjectClass
(as in your code) to get a reference to the class java.lang.Integer and then GetMethodID
and CallObjectMethod
to actually invoke the intValue
method.
这篇关于JNI如何访问Java Object(Integer)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!