Last active
September 30, 2016 21:23
-
-
Save itsff/7b912b4f9e8731023306f67064e38ffa to your computer and use it in GitHub Desktop.
RAII JNI string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <jni.h> | |
class jni_string | |
{ | |
public: | |
jni_string (JNIEnv *env, | |
jstring javaString) | |
: _env(env) | |
, _javaString(javaString) | |
{ | |
_nativeString = _env->GetStringUTFChars(_javaString, 0); | |
} | |
~jni_string () | |
{ | |
if (_nativeString) | |
{ | |
_env->ReleaseStringUTFChars(_javaString, _nativeString); | |
} | |
} | |
jni_string (jni_string && other) | |
: _env(std::move(other._env)) | |
, _javaString(std::move(other._javaString)) | |
, _nativeString(std::move(other._nativeString)) | |
{ | |
other._nativeString = nullptr; | |
} | |
jni_string & | |
operator= (jni_string && other) | |
{ | |
if (&other != this) | |
{ | |
_env = std::move(other._env); | |
_javaString = std::move(other._javaString); | |
_nativeString = std::move(other._nativeString); | |
other._nativeString = nullptr; | |
} | |
return *this; | |
} | |
operator const char *() const { return _nativeString; } | |
const char * const c_str () const { return _nativeString; } | |
private: | |
jni_string (const jni_string &x) = delete; | |
jni_string &operator=(const jni_string &x) = delete; | |
private: | |
JNIEnv * _env; | |
jstring _javaString; | |
const char * _nativeString; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment