英文:
JNI - How to get the Double.toString() method to convert a jdouble to a jstring
问题
jdouble result;
// 获取Double类的Class对象,以便获取toString()方法的方法ID。
jclass doubleObjectClass = env->GetObjectClass(env->FindClass("java/lang/Double"));
// 获取Double.toString()方法的方法ID。
jmethodID doubleToStringMethodID = env->GetMethodID(doubleObjectClass, "toString", "()Ljava/lang/String;");
// 在result上调用toString()方法。
jstring newString = (jstring) env->CallObjectMethod(doubleObjectClass, doubleToStringMethodID, result);
英文:
So I want to be able to convert a jdouble to a jstring using
the inbuilt Double.toString() from c++.
This is how I think I would do it.
jdouble result;
//Get the class for Double so we can get the method id of toString().
jclass doubleObjectClass = env->GetObjectClass("Ljava/lang/Double;");
//Get the Double.toString() method ID.
jmethodID doubleToStringMethodID = env->GetMethodID(doubleObjectClass, "toString",(Ljava/lang/String;");
//Call the toString() method on result.
jstring newString = env->CallObjectMethod(..., doubleToStringMethodID, result);
Now the problem is what is happening when I call getObjectClass & CallObjectMethod.
With getObjectClass, from memory it needs to take in a jobject, not a descript.
And with CallObjectMethod we need the Double object as a parameter (where '...' is).
So I don't know how to proceed as the documentation isn't helping atm.
Any help would be great thanks!
答案1
得分: 2
你在拥有具体的jobject
访问权限时使用GetObjectClass
。如果你只有类名,那就是使用FindClass
函数与类的二进制名称。你正在查找静态方法ID,因此需要使用不同的函数(GetStaticMethodID
和CallStaticMethodID
)。最后,方法签名必须正确。
将所有内容组合起来:
jdouble result;
jclass doubleObjectClass = env->FindClass("java/lang/Double");
jmethodID doubleToStringMethodID = env->GetStaticMethodID(doubleObjectClass, "toString", "(D)Ljava/lang/String;");
jstring newString = env->CallStaticObjectMethod(doubleObjectClass, doubleToStringMethodID, result);
英文:
You use GetObjectClass
when you have access to concrete jobject
. If you only have a class name, that is the FindClass
function with the class' binary name. You are looking up a static method ID, so that is a different set of functions (GetStaticMethodID
and CallStaticMethodID
). Finally, the method signature must be correct.
Putting it all together:
jdouble result;
jclass doubleObjectClass = env->FindClass("java/lang/Double");
jmethodID doubleToStringMethodID = env->GetStaticMethodID(doubleObjectClass, "toString","(D)Ljava/lang/String;");
jstring newString = env->CallStaticObjectMethod(doubleObjectClass, doubleToStringMethodID, result);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论