I have a c++ class called androidGPS with public methods and variables. Inside this class I am using JNI to calls some java code. But I am stuck in the registerNatives function.
My c++ class has this void method:
void LocationChanged(JNIEnv* env, jobject object, jstring paramsString);
Implemented in this way:
void androidGPS::LocationChanged(JNIEnv*, jobject, jstring paramsString)
{
const char * nativeString = currEnv->GetStringUTFChars(paramsString, 0);
QString qstring(nativeString);
QStringList res;
res << qstring;
emit newReadAvailable(res);
}
The Java class that I try to link to has the following method:
public static native void sndonLocationChanged(String currLocation);
I am declaring the JNINativeMethods as a local variable before calling the register natives like:
JNINativeMethod methods[] =
{
{
"sndonLocationChanged",
"(Ljava/lang/String;)V",
(void *)&androidGPS::LocationChanged
}
};
The register natives call is this:
int numMethods;
numMethods = sizeof(methods) / sizeof(methods[0]);
if (currEnv->RegisterNatives(listenerClass, methods, numMethods) < 0)
{
if (currEnv->ExceptionOccurred())
{
classError = true;
emit error("JNI--Error running RegisterNatives");
stopGPSService();
return false; //Return with error
}
else
{
emit error("JNI--Error running RegisterNatives");
stopGPSService();
return false; //Return with error
}
}
The compiler gives 开发者_如何学Cme the warning:
warning: converting from 'void (androidGPS::)(JNIEnv, _jobject*, _jstring*)' to 'void*'
The c++ application crashes when I call the function sndonLocationChanged() in the class through JNI. I cannot see the error in the c++, but the Dalvik does not generate an error.
I guess is because I am not calling properly registerNatives or not declaring properly the methods (hence the warning).
If I declare LocationChanged static as:
static jboolean LocationChanged(JNIEnv* env, jobject object, jstring paramsString);
It does not fail but I cannot pass paramsString into class members!
Any idea how can I fix this?
Many thanks,
Carlos.
One option is that you give your Java code a means of getting a pointer to your native androidGPS object and passing it down to the non-class-function LocationChanged(), and it calls androidGPS::LocationChanged().
Callbacks into non-static C++ objects are problematic and typically are solved using a static helper function coupled with either a pointer to the object that the callback should be invoked on, or use of a static pointer to a singleton object.
精彩评论