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_included 18 #define SCOPED_STRING_CHARS_H_included 19 20 #include "JNIHelp.h" 21 22 // A smart pointer that provides access to a jchar* given a JNI jstring. 23 class ScopedStringChars { 24 public: ScopedStringChars(JNIEnv * env,jstring s)25 ScopedStringChars(JNIEnv* env, jstring s) : mEnv(env), mString(s), mSize(0) { 26 mChars = env->GetStringChars(mString, NULL); 27 if (mChars != NULL) { 28 mSize = env->GetStringLength(mString); 29 } 30 } 31 ~ScopedStringChars()32 ~ScopedStringChars() { 33 mEnv->ReleaseStringChars(mString, mChars); 34 } 35 get()36 const jchar* get() const { return mChars; } 37 const jchar& operator[](size_t n) const { return mChars[n]; } size()38 size_t size() const { return mSize; } 39 40 private: 41 JNIEnv* mEnv; 42 jstring mString; 43 const jchar* mChars; 44 size_t mSize; 45 46 // Disallow copy and assignment. 47 ScopedStringChars(const ScopedStringChars&); 48 void operator=(const ScopedStringChars&); 49 }; 50 51 #endif // SCOPED_STRING_CHARS_H_included 52