/** * @file jni.cpp * @author myusgun@gmail.com * @brief JNI */ #ifdef _USE_JNI #include "cf/jni.h" #include "cf/types.h" #include #include using namespace cf; #define USE_JNI_PRIMITIVE cf::void_t jni::releaseByteArray(jbyteArray jinput, cf::char_t * in) { if(!jinput || !in) return; #ifdef USE_JNI_PRIMITIVE mJNIEnv->ReleasePrimitiveArrayCritical((jarray)jinput, (cf::void_t *)in, JNI_ABORT); #else mJNIEnv->ReleaseByteArrayElements(jinput, (jbyte *)in, JNI_ABORT); #endif } cf::void_t jni::releaseString(jstring jinput, cf::char_t * in) { if(!jinput || !in) return; mJNIEnv->ReleaseStringUTFChars(jinput, in); } cf::void_t jni::releaseLocalMemory(jobject in) { /* collected by GC */ #if 0 mJNIEnv->DeleteLocalRef(in); #endif } bin jni::getByteArray(jbyteArray jinput) throw (exception) { jboolean isCopy; bin out; cf::char_t * buf = NULL; cf::int32_t len = 0; if(!jinput) THROW_EXCEPTION("input from java is null"); #ifdef USE_JNI_PRIMITIVE /** * NOTE * read-only */ isCopy = JNI_FALSE; buf = (cf::char_t *)mJNIEnv->GetPrimitiveArrayCritical((jarray)jinput, &isCopy); if(!buf) THROW_EXCEPTION("failed to GetPrimitiveArrayCritical"); #else buf = (cf::char_t *)mJNIEnv->GetByteArrayElements(jinput, &isCopy); #endif len = (cf::int32_t)mJNIEnv->GetArrayLength(jinput); out.copy((cf::uint8_t *)buf, len); releaseByteArray(jinput, buf); return out; } std::string jni::getString(jstring jinput) throw (exception) { if(!jinput) THROW_EXCEPTION("input from java is null"); jboolean isCopy; cf::char_t * buf = (cf::char_t *)mJNIEnv->GetStringUTFChars(jinput, &isCopy); std::string out = buf; releaseString(jinput, buf); return out; } cf::void_t jni::throwException(const cf::char_t * message) { jthrowable occurred = mJNIEnv->ExceptionOccurred(); if(occurred) mJNIEnv->Throw(occurred); jclass exClass = mJNIEnv->FindClass("java/lang/Exception"); mJNIEnv->ThrowNew(exClass, message); } jbyteArray jni::newByteArray(const bin & in) { jbyteArray out = NULL; out = mJNIEnv->NewByteArray((jsize)in.length()); if(!out) return NULL; mJNIEnv->SetByteArrayRegion(out, 0, (jsize)in.length(), (jbyte *)in.value()); return out; } jstring jni::newString(const std::string & in) { return mJNIEnv->NewStringUTF(in.c_str()); } #endif // #ifdef _USE_JNI