Search code examples
javac++java-native-interfacedoubletostring

JNI - How to get the Double.toString() method to convert a jdouble to a jstring


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!


Solution

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