Get Java Array From C++ Via Jni
Solution 1:
First you have to get a reference to the class providing the method. Let's say your class is called MyClass and it is in package p. You get the reference to the class like this:
// You get the JNIEnv* pointer when calling a native function.jclassmyClass= env->FindClass("p/MyClass");
Or if you have a reference to the java object then you can also use GetObjectClass
:
jclass myClass = env->GetObjectClass(javaObject);
Then you have to get the ID of the method you'd like to call by providing the name of the method and a string describing the signature of the method.
"()[java/lang/String;" describes a method expecting no arguments and returning a stringarray.
jmethodID methodID = env->GetMethodID(myClass , "searchDatabase", "()[java/lang/String;");
Then you have to call the method with JNIEnv::CallObjectMethod
, and here you have to pass the referenc to the java object.
jobjectarray strings = env->CallObjectMethod(javaObject, methodID);
Then you can get an element of the array with GetObjectArrayElement
.
intindex = 0;
jstring string = env->GetObjectArrayElement(strings, index);
And then you can get the native string from it in various ways.
constchar* nativeChars = env->GetStringUTFChars(string, nullptr);
You can find more information about JNI here, and details about JNI type signatures here.
Solution 2:
I believe you could do it by passing back a jobjectArray.
int elements = 5;
jobjectArray returnArray = (jobjectArray)env->NewObjectArray(elements, env->FindClass("java/lang/string"), env->NewStringUTF(""));
for(int i = 0; i < elements; i++)
{
charstr[12];
sprintf(str, "%i", i);
env->SetObjectArrayElment(returnArray, i, env->NewStringUTF(str));
}
return returnArray;
I've only done this with a byte array
Post a Comment for "Get Java Array From C++ Via Jni"