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.
| 409 | // This is the C++ handler which will be called by clientSML when the event fires. |
| 410 | // Then from here we need to call back to Java to pass back the message. |
| 411 | static void ProductionEventHandler(sml::smlProductionEventId id, void* pUserData, sml::Agent* pAgent, char const* pProdName, char const* pInstantiation) |
| 412 | { |
| 413 | // The user data is the class we declared above, where we store the Java data to use in the callback. |
| 414 | JavaCallbackData* pJavaData = (JavaCallbackData*)pUserData ; |
| 415 | |
| 416 | // Now try to call back to Java |
| 417 | JNIEnv* jenv = pJavaData->GetEnv() ; |
| 418 | |
| 419 | // We start from the Java object whose method we wish to call. |
| 420 | jobject jobj = pJavaData->m_HandlerObject ; |
| 421 | jclass cls = jenv->GetObjectClass(jobj) ; |
| 422 | |
| 423 | if (cls == 0) |
| 424 | { |
| 425 | printf("Failed to get Java class\n") ; |
| 426 | return ; |
| 427 | } |
| 428 | |
| 429 | // Look up the Java method we want to call. |
| 430 | // The method name is passed in by the user (and needs to match exactly, including case). |
| 431 | // The method should be owned by the m_HandlerObject that the user also passed in. |
| 432 | // Any slip here and you get a NoSuchMethod exception and my Java VM shuts down. |
| 433 | jmethodID mid = jenv->GetMethodID(cls, pJavaData->m_HandlerMethod.c_str(), "(ILjava/lang/Object;Lsml/Agent;Ljava/lang/String;Ljava/lang/String;)V") ; |
| 434 | |
| 435 | if (mid == 0) |
| 436 | { |
| 437 | printf("Failed to get Java method\n") ; |
| 438 | return ; |
| 439 | } |
| 440 | |
| 441 | // Convert our C++ strings to Java strings |
| 442 | jstring prod = pProdName != NULL ? jenv->NewStringUTF(pProdName) : 0 ; |
| 443 | jstring inst = pInstantiation != NULL ? jenv->NewStringUTF(pInstantiation) : 0 ; |
| 444 | |
| 445 | // Make the method call. |
| 446 | jenv->CallVoidMethod(jobj, mid, (int)id, pJavaData->m_CallbackData, pJavaData->m_AgentObject, prod, inst); |
| 447 | |
| 448 | // Cleaning up the local references just in case |
| 449 | jenv->DeleteLocalRef(prod); |
| 450 | jenv->DeleteLocalRef(inst); |
| 451 | } |
| 452 | |
| 453 | // This is the hand-written JNI method for registering a callback. |
| 454 | // I'm going to model it after the existing SWIG JNI methods so hopefully it'll be easier to patch this into SWIG eventually. |