|
| 1 | +#include "exception.h" |
| 2 | + |
| 3 | +enum class JavaType { |
| 4 | + Int, |
| 5 | + Byte, |
| 6 | + Char, |
| 7 | + Double, |
| 8 | + Float, |
| 9 | + Long, |
| 10 | + String, |
| 11 | + Short, |
| 12 | + Void, |
| 13 | + Boolean |
| 14 | +}; |
| 15 | + |
| 16 | +static const char* mapJavaTypeToString(JavaType type) { |
| 17 | + switch (type) { |
| 18 | + case JavaType::Int: return "I"; |
| 19 | + case JavaType::Byte: return "B"; |
| 20 | + case JavaType::Char: return "C"; |
| 21 | + case JavaType::Double: return "D"; |
| 22 | + case JavaType::Float: return "F"; |
| 23 | + case JavaType::Long: return "J"; |
| 24 | + case JavaType::String: return "Ljava/lang/String;"; |
| 25 | + case JavaType::Short: return "S"; |
| 26 | + case JavaType::Void: return "V"; |
| 27 | + case JavaType::Boolean: return "B"; |
| 28 | + default: throw std::logic_error("Unknown Java Type"); |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +static std::string generateFunctionSignature(JavaType returnType, |
| 33 | + std::initializer_list<JavaType> params) { |
| 34 | + std::string signature = "("; |
| 35 | + for (const auto& param : params) { signature += mapJavaTypeToString(param); } |
| 36 | + signature += ")"; |
| 37 | + signature += mapJavaTypeToString(returnType); |
| 38 | + return signature; |
| 39 | +} |
| 40 | + |
| 41 | +void JavaException::throwArrayFireException(JNIEnv *env, const char *functionName, const char *file, |
| 42 | + const int line, const int code) { |
| 43 | + //Find and instantiate an ArrayFireException |
| 44 | + jclass exceptionClass = env->FindClass("com/arrayfire/ArrayFireException"); |
| 45 | + if (env->ExceptionCheck()) { |
| 46 | + env->ExceptionDescribe(); |
| 47 | + } |
| 48 | + |
| 49 | + const std::string constructorSig = generateFunctionSignature(JavaType::Void, { |
| 50 | + JavaType::Int, JavaType::String |
| 51 | + }); |
| 52 | + jmethodID constructor = env->GetMethodID(exceptionClass, "<init>", constructorSig.c_str()); |
| 53 | + |
| 54 | + jthrowable exception = reinterpret_cast<jthrowable>( |
| 55 | + env->NewObject(exceptionClass, |
| 56 | + constructor, |
| 57 | + code, |
| 58 | + env->NewStringUTF("Some custom message here."))); |
| 59 | + |
| 60 | + // Find setLocation method and call it with |
| 61 | + // the function name, file and line parameters |
| 62 | + const std::string setLocationSig = generateFunctionSignature(JavaType::Void, { |
| 63 | + JavaType::String, JavaType::String, JavaType::Int |
| 64 | + }); |
| 65 | + jmethodID setLocationID = env->GetMethodID(exceptionClass, "setLocation", setLocationSig.c_str()); |
| 66 | + env->CallVoidMethod(exception, setLocationID, env->NewStringUTF(functionName), |
| 67 | + env->NewStringUTF(file), line); |
| 68 | + |
| 69 | + env->Throw(exception); |
| 70 | + env->DeleteLocalRef(exceptionClass); |
| 71 | + } |
0 commit comments