blob: cb46024fef8c243256039041785fb20f21b097d9 [file] [log] [blame]
Brian Carlstromdd8af232012-05-13 23:56:07 -07001/*
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
26jobjectArray newStringArray(JNIEnv* env, size_t count);
27
28template <typename Counter, typename Getter>
29jobjectArray 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
Ian Rogers5d6c98a2014-05-16 17:58:48 -070048struct VectorCounter {
49 const std::vector<std::string>& strings;
Chih-Hung Hsiehb493dac2016-06-30 14:50:40 -070050 explicit VectorCounter(const std::vector<std::string>& strings) : strings(strings) {}
Ian Rogers5d6c98a2014-05-16 17:58:48 -070051 size_t operator()() {
52 return strings.size();
53 }
54};
55struct VectorGetter {
56 const std::vector<std::string>& strings;
Chih-Hung Hsiehb493dac2016-06-30 14:50:40 -070057 explicit VectorGetter(const std::vector<std::string>& strings) : strings(strings) {}
Ian Rogers5d6c98a2014-05-16 17:58:48 -070058 const char* operator()(size_t i) {
59 return strings[i].c_str();
60 }
61};
62
63inline 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
Brian Carlstromdd8af232012-05-13 23:56:07 -070069JNIEXPORT jobjectArray toStringArray(JNIEnv* env, const char* const* strings);
70
71#endif // TO_STRING_ARRAY_H_included