source: libcf++/trunk/src/jni.cpp@ 4

Last change on this file since 4 was 4, checked in by cheese, 9 years ago

#1 commit prototype

File size: 2.3 KB
Line 
1/**
2 * @file jni.cpp
3 * @author myusgun@gmail.com
4 * @brief JNI
5 */
6#ifdef _USE_JNI
7#include "cf/jni.h"
8#include "cf/types.h"
9
10#include <stdio.h>
11#include <stdarg.h>
12
13using namespace cf;
14
15#define USE_JNI_PRIMITIVE
16
17cf::void_t jni::releaseByteArray(jbyteArray jinput,
18 cf::char_t * in)
19{
20 if(!jinput || !in)
21 return;
22
23#ifdef USE_JNI_PRIMITIVE
24 mJNIEnv->ReleasePrimitiveArrayCritical((jarray)jinput, (cf::void_t *)in, JNI_ABORT);
25#else
26 mJNIEnv->ReleaseByteArrayElements(jinput, (jbyte *)in, JNI_ABORT);
27#endif
28}
29
30cf::void_t jni::releaseString(jstring jinput,
31 cf::char_t * in)
32{
33 if(!jinput || !in)
34 return;
35
36 mJNIEnv->ReleaseStringUTFChars(jinput, in);
37}
38
39cf::void_t jni::releaseLocalMemory(jobject in)
40{
41 /* collected by GC */
42#if 0
43 mJNIEnv->DeleteLocalRef(in);
44#endif
45}
46
47bin jni::getByteArray(jbyteArray jinput)
48 throw (exception)
49{
50 jboolean isCopy;
51 bin out;
52
53 cf::char_t * buf = NULL;
54 cf::int32_t len = 0;
55
56 if(!jinput)
57 THROW_EXCEPTION("input from java is null");
58
59#ifdef USE_JNI_PRIMITIVE
60 /**
61 * NOTE
62 * read-only
63 */
64 isCopy = JNI_FALSE;
65 buf = (cf::char_t *)mJNIEnv->GetPrimitiveArrayCritical((jarray)jinput, &isCopy);
66 if(!buf)
67 THROW_EXCEPTION("failed to GetPrimitiveArrayCritical");
68#else
69 buf = (cf::char_t *)mJNIEnv->GetByteArrayElements(jinput, &isCopy);
70#endif
71 len = (cf::int32_t)mJNIEnv->GetArrayLength(jinput);
72
73 out.copy((cf::uint8_t *)buf, len);
74
75 releaseByteArray(jinput, buf);
76
77 return out;
78}
79
80std::string jni::getString(jstring jinput)
81 throw (exception)
82{
83 if(!jinput)
84 THROW_EXCEPTION("input from java is null");
85
86 jboolean isCopy;
87 cf::char_t * buf = (cf::char_t *)mJNIEnv->GetStringUTFChars(jinput, &isCopy);
88 std::string out = buf;
89
90 releaseString(jinput, buf);
91
92 return out;
93}
94
95cf::void_t jni::throwException(const cf::char_t * message)
96{
97 jthrowable occurred = mJNIEnv->ExceptionOccurred();
98 if(occurred)
99 mJNIEnv->Throw(occurred);
100
101 jclass exClass = mJNIEnv->FindClass("java/lang/Exception");
102
103 mJNIEnv->ThrowNew(exClass, message);
104}
105
106jbyteArray jni::newByteArray(const bin & in)
107{
108 jbyteArray out = NULL;
109
110 out = mJNIEnv->NewByteArray((jsize)in.length());
111 if(!out)
112 return NULL;
113
114 mJNIEnv->SetByteArrayRegion(out, 0, (jsize)in.length(), (jbyte *)in.value());
115
116 return out;
117}
118
119jstring jni::newString(const std::string & in)
120{
121 return mJNIEnv->NewStringUTF(in.c_str());
122}
123
124#endif // #ifdef _USE_JNI
Note: See TracBrowser for help on using the repository browser.