diff options
-rw-r--r-- | header_only_include/nativehelper/scoped_utf_chars.h | 10 | ||||
-rw-r--r-- | header_only_include/nativehelper/utils.h | 8 |
2 files changed, 17 insertions, 1 deletions
diff --git a/header_only_include/nativehelper/scoped_utf_chars.h b/header_only_include/nativehelper/scoped_utf_chars.h index 8f9fc70..25de0fc 100644 --- a/header_only_include/nativehelper/scoped_utf_chars.h +++ b/header_only_include/nativehelper/scoped_utf_chars.h @@ -23,6 +23,11 @@ #include "nativehelper_utils.h" +// Protect this with __has_include to cope with `stl: "none"` users. +#if __has_include(<string_view>) +#include <string_view> +#endif + // A smart pointer that provides read-only access to a Java string's UTF chars. // Unlike GetStringUTFChars, we throw NullPointerException rather than abort if // passed a null jstring, and c_str will return nullptr. @@ -86,6 +91,10 @@ class ScopedUtfChars { return utf_chars_[n]; } +#if __has_include(<string_view>) + operator std::string_view() const { return utf_chars_; } +#endif + private: JNIEnv* env_; jstring string_; @@ -93,4 +102,3 @@ class ScopedUtfChars { DISALLOW_COPY_AND_ASSIGN(ScopedUtfChars); }; - diff --git a/header_only_include/nativehelper/utils.h b/header_only_include/nativehelper/utils.h index b01c060..30f239e 100644 --- a/header_only_include/nativehelper/utils.h +++ b/header_only_include/nativehelper/utils.h @@ -89,6 +89,14 @@ class JniDefaultValue { // ScopedUtfChars str = GET_UTF_OR_RETURN_VOID(env, j_str); // // Safely use `str` here... // } +// +// The idiomatic way to construct an `std::string` using this macro (an additional string copy is +// performed): +// +// jobject MyJniMethod(JNIEnv* env, jstring j_str) { +// std::string str(GET_UTF_OR_RETURN(env, j_str)); +// // Safely use `str` here... +// } #define GET_UTF_OR_RETURN(env, expr) \ GET_UTF_OR_RETURN_IMPL_((env), (expr), android::jnihelp::JniDefaultValue()) #define GET_UTF_OR_RETURN_VOID(env, expr) GET_UTF_OR_RETURN_IMPL_((env), (expr)) |