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.
| 1014 | // This is the C++ handler which will be called by clientSML when the event fires. |
| 1015 | // Then from here we need to call back to Java to pass back the message. |
| 1016 | static std::string StringEventHandler(sml::smlStringEventId id, void* pUserData, sml::Kernel* pKernel, char const* pData) |
| 1017 | { |
| 1018 | // The user data is the class we declared above, where we store the Java data to use in the callback. |
| 1019 | JavaCallbackData* pJavaData = (JavaCallbackData*)pUserData ; |
| 1020 | |
| 1021 | // Now try to call back to Java |
| 1022 | JNIEnv* jenv = pJavaData->GetEnv() ; |
| 1023 | |
| 1024 | // We start from the Java object whose method we wish to call. |
| 1025 | jobject jobj = pJavaData->m_HandlerObject ; |
| 1026 | jclass cls = jenv->GetObjectClass(jobj) ; |
| 1027 | |
| 1028 | if (cls == 0) |
| 1029 | { |
| 1030 | printf("Failed to get Java class\n") ; |
| 1031 | return "Error -- failed to get Java class"; |
| 1032 | } |
| 1033 | |
| 1034 | // Look up the Java method we want to call. |
| 1035 | // The method name is passed in by the user (and needs to match exactly, including case). |
| 1036 | // The method should be owned by the m_HandlerObject that the user also passed in. |
| 1037 | // Any slip here and you get a NoSuchMethod exception and my Java VM shuts down. |
| 1038 | jmethodID mid = jenv->GetMethodID(cls, pJavaData->m_HandlerMethod.c_str(), "(ILjava/lang/Object;Lsml/Kernel;Ljava/lang/String;)Ljava/lang/String;") ; |
| 1039 | |
| 1040 | if (mid == 0) |
| 1041 | { |
| 1042 | printf("Failed to get Java method\n") ; |
| 1043 | return "Error -- failed to get Java method"; |
| 1044 | } |
| 1045 | |
| 1046 | // Create the string to return to the caller |
| 1047 | jstring data = pData != NULL ? jenv->NewStringUTF(pData) : 0 ; |
| 1048 | |
| 1049 | // Make the method call. |
| 1050 | jstring result = (jstring)jenv->CallObjectMethod(jobj, mid, (int)id, pJavaData->m_CallbackData, pJavaData->m_KernelObject, data); |
| 1051 | |
| 1052 | // Get the returned string |
| 1053 | std::string resultStr = "" ; |
| 1054 | |
| 1055 | if (result != 0) |
| 1056 | { |
| 1057 | // Get the C string |
| 1058 | char const* pResult = jenv->GetStringUTFChars(result, 0); |
| 1059 | |
| 1060 | // Copy it into our std::string |
| 1061 | resultStr = pResult ; |
| 1062 | |
| 1063 | // Release the Java string |
| 1064 | jenv->ReleaseStringUTFChars(result, pResult); |
| 1065 | } |
| 1066 | |
| 1067 | // Cleaning up the local references just in case |
| 1068 | jenv->DeleteLocalRef(data); |
| 1069 | |
| 1070 | // Return the result |
| 1071 | return resultStr ; |
| 1072 | |
| 1073 | } |