Home | History | Annotate | Download | only in nativehelper
      1 /*
      2  * Copyright (C) 2011 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #ifndef TO_STRING_ARRAY_H_included
     18 #define TO_STRING_ARRAY_H_included
     19 
     20 #include "jni.h"
     21 #include "ScopedLocalRef.h"
     22 
     23 #include <string>
     24 #include <vector>
     25 
     26 jobjectArray newStringArray(JNIEnv* env, size_t count);
     27 
     28 template <typename Counter, typename Getter>
     29 jobjectArray toStringArray(JNIEnv* env, Counter* counter, Getter* getter) {
     30     size_t count = (*counter)();
     31     jobjectArray result = newStringArray(env, count);
     32     if (result == NULL) {
     33         return NULL;
     34     }
     35     for (size_t i = 0; i < count; ++i) {
     36         ScopedLocalRef<jstring> s(env, env->NewStringUTF((*getter)(i)));
     37         if (env->ExceptionCheck()) {
     38             return NULL;
     39         }
     40         env->SetObjectArrayElement(result, i, s.get());
     41         if (env->ExceptionCheck()) {
     42             return NULL;
     43         }
     44     }
     45     return result;
     46 }
     47 
     48 template <typename Counter, typename Getter>
     49 jobjectArray toStringArray16(JNIEnv* env, Counter* counter, Getter* getter) {
     50     size_t count = (*counter)();
     51     jobjectArray result = newStringArray(env, count);
     52     if (result == NULL) {
     53         return NULL;
     54     }
     55     for (size_t i = 0; i < count; ++i) {
     56         int32_t charCount;
     57         const jchar* chars = (*getter)(&charCount);
     58         ScopedLocalRef<jstring> s(env, env->NewString(chars, charCount));
     59         if (env->ExceptionCheck()) {
     60             return NULL;
     61         }
     62         env->SetObjectArrayElement(result, i, s.get());
     63         if (env->ExceptionCheck()) {
     64             return NULL;
     65         }
     66     }
     67     return result;
     68 }
     69 
     70 JNIEXPORT jobjectArray toStringArray(JNIEnv* env, const std::vector<std::string>& strings);
     71 JNIEXPORT jobjectArray toStringArray(JNIEnv* env, const char* const* strings);
     72 
     73 #endif  // TO_STRING_ARRAY_H_included
     74