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 struct VectorCounter { 49 const std::vector<std::string>& strings; 50 VectorCounter(const std::vector<std::string>& strings) : strings(strings) {} 51 size_t operator()() { 52 return strings.size(); 53 } 54 }; 55 struct VectorGetter { 56 const std::vector<std::string>& strings; 57 VectorGetter(const std::vector<std::string>& strings) : strings(strings) {} 58 const char* operator()(size_t i) { 59 return strings[i].c_str(); 60 } 61 }; 62 63 inline jobjectArray toStringArray(JNIEnv* env, const std::vector<std::string>& strings) { 64 VectorCounter counter(strings); 65 VectorGetter getter(strings); 66 return toStringArray<VectorCounter, VectorGetter>(env, &counter, &getter); 67 } 68 69 JNIEXPORT jobjectArray toStringArray(JNIEnv* env, const char* const* strings); 70 71 #endif // TO_STRING_ARRAY_H_included 72