This is the C++ handler which will be called by clientSML when the event fires. Then from here we need to call back to Java to pass back the message.
| 497 | // This is the C++ handler which will be called by clientSML when the event fires. |
| 498 | // Then from here we need to call back to Java to pass back the message. |
| 499 | static void PrintEventHandler(sml::smlPrintEventId id, void* pUserData, sml::Agent* pAgent, char const* pMessage) |
| 500 | { |
| 501 | // The user data is the class we declared above, where we store the Java data to use in the callback. |
| 502 | JavaCallbackData* pJavaData = (JavaCallbackData*)pUserData ; |
| 503 | |
| 504 | // Now try to call back to Java |
| 505 | JNIEnv* jenv = pJavaData->GetEnv() ; |
| 506 | |
| 507 | // We start from the Java object whose method we wish to call. |
| 508 | jobject jobj = pJavaData->m_HandlerObject ; |
| 509 | jclass cls = jenv->GetObjectClass(jobj) ; |
| 510 | |
| 511 | if (cls == 0) |
| 512 | { |
| 513 | printf("Failed to get Java class\n") ; |
| 514 | return ; |
| 515 | } |
| 516 | |
| 517 | // Look up the Java method we want to call. |
| 518 | // The method name is passed in by the user (and needs to match exactly, including case). |
| 519 | // The method should be owned by the m_HandlerObject that the user also passed in. |
| 520 | // Any slip here and you get a NoSuchMethod exception and my Java VM shuts down. |
| 521 | jmethodID mid = jenv->GetMethodID(cls, pJavaData->m_HandlerMethod.c_str(), "(ILjava/lang/Object;Lsml/Agent;Ljava/lang/String;)V") ; |
| 522 | |
| 523 | if (mid == 0) |
| 524 | { |
| 525 | printf("Failed to get Java method\n") ; |
| 526 | return ; |
| 527 | } |
| 528 | |
| 529 | // Convert our C++ strings to Java strings |
| 530 | jstring message = pMessage != NULL ? jenv->NewStringUTF(pMessage) : 0 ; |
| 531 | |
| 532 | // Make the method call. |
| 533 | jenv->CallVoidMethod(jobj, mid, (int)id, pJavaData->m_CallbackData, pJavaData->m_AgentObject, message); |
| 534 | |
| 535 | // Cleaning up the local references just in case |
| 536 | jenv->DeleteLocalRef(message); |
| 537 | } |
| 538 | |
| 539 | // This is the hand-written JNI method for registering a callback. |
| 540 | // I'm going to model it after the existing SWIG JNI methods so hopefully it'll be easier to patch this into SWIG eventually. |