Wednesday, April 24, 2013

jni jnienv GetStringCritical example c c++ java


GetStringCritical
ReleaseStringCritical

const jchar * GetStringCritical(JNIEnv *env, jstring string, jboolean *isCopy);
void ReleaseStringCritical(JNIEnv *env, jstring string, const jchar *carray);
The semantics of these two functions are similar to the existing Get/ReleaseStringChars functions. If possible, the VM returns a pointer to string elements; otherwise, a copy is made. However, there are significant restrictions on how these functions can be used. In a code segment enclosed by Get/ReleaseStringCritical calls, the native code must not issue arbitrary JNI calls, or cause the current thread to block.
The restrictions on Get/ReleaseStringCritical are similar to those on Get/ReleasePrimitiveArrayCritical.
LINKAGE (GetStringCritical):
Index 224 in the JNIEnv interface function table.
LINKAGE (ReleaseStingCritical):
Index 225 in the JNIEnv interface function table.

Example of GetStringCritical
/**
*   Wraps Get/ReleaseStringCritical pairs of unicode java-string
*/
struct jniCriticalString
{
    jniCriticalString(JNIEnv *env, jstring str):
        _env(env),
        _str(str)
    {
        _pstr = _env->GetStringCritical(_str, &_is_copy);
    }
    ~jniCriticalString()
    {
        if( _pstr != NULL )
        {
            _env->ReleaseStringCritical(_str, _pstr);
        }
    }
    /**
    *   True, if wrapped string is valid - e.g. call of GetStringCritical returned valid value
    */
    bool is_valid() const
    {
        return _pstr != NULL;
    }
    /** True when GetStringCritical created copy instead of direct pointer */
    bool is_copy() const
    {
        return _is_copy == JNI_TRUE;
    }
    /** Return unicode NOT NULL TERMINATED! string.*/
    const wchar_t* c_str() const
    {
        return reinterpret_cast<const wchar_t*>( _pstr );
    }
    /** Get the length of internal string */
    jsize length() const
    {
        return _env->GetStringLength(_str);
    }
    std::wstring as_string() const
    {
        return std::wstring(c_str(), length());
    }
    operator std::wstring () const
    {
        return as_string();
    }

private:
    JNIEnv *_env;
    jstring _str;
    jboolean _is_copy;
    const jchar *_pstr;
};