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 SCOPED_STRING_CHARS_H_ 18 #define SCOPED_STRING_CHARS_H_ 19 20 #include "jni.h" 21 #include "nativehelper_utils.h" 22 23 // A smart pointer that provides access to a jchar* given a JNI jstring. 24 // Unlike GetStringChars, we throw NullPointerException rather than abort if 25 // passed a null jstring, and get will return NULL. 26 // This makes the correct idiom very simple: 27 // 28 // ScopedStringChars name(env, java_name); 29 // if (name.get() == NULL) { 30 // return NULL; 31 // } 32 class ScopedStringChars { 33 public: ScopedStringChars(JNIEnv * env,jstring s)34 ScopedStringChars(JNIEnv* env, jstring s) : env_(env), string_(s), size_(0) { 35 if (s == NULL) { 36 chars_ = NULL; 37 jniThrowNullPointerException(env, NULL); 38 } else { 39 chars_ = env->GetStringChars(string_, NULL); 40 if (chars_ != NULL) { 41 size_ = env->GetStringLength(string_); 42 } 43 } 44 } 45 ~ScopedStringChars()46 ~ScopedStringChars() { 47 if (chars_ != NULL) { 48 env_->ReleaseStringChars(string_, chars_); 49 } 50 } 51 get()52 const jchar* get() const { 53 return chars_; 54 } 55 size()56 size_t size() const { 57 return size_; 58 } 59 60 const jchar& operator[](size_t n) const { 61 return chars_[n]; 62 } 63 64 private: 65 JNIEnv* const env_; 66 const jstring string_; 67 const jchar* chars_; 68 size_t size_; 69 70 DISALLOW_COPY_AND_ASSIGN(ScopedStringChars); 71 }; 72 73 #endif // SCOPED_STRING_CHARS_H_ 74