JNI – 如何使得Double.toString()方法将jdouble转换为jstring

huangapple go评论85阅读模式
英文:

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,因此需要使用不同的函数(GetStaticMethodIDCallStaticMethodID)。最后,方法签名必须正确。

将所有内容组合起来:

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);

huangapple
  • 本文由 发表于 2020年10月21日 19:32:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/64462637.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定