How to return a java string in C++ using JNI -
i need call java code , return string c++ using jni.
basically in c++ want use function "string getmystring()"
obtain string java. how obtain ?
follow wrapper return std::wstring. note uses "critical string"
/** * 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 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 ); } /** 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; };
updated
following code uses string input parameter:
java code:
private static native void log_message( string category, string message, int level);
c++ impl:
jniexport void jnicall java_bla_bla_bla_bla_log_1message (jnienv *env, jclass, jstring category, jstring message, jint level) { jnicriticalstring pcat(env, category); if( !pcat.is_valid() ) return; jnicriticalstring pmsg(env, message); if( !pmsg.is_valid() ) return; std::wstring lcat(pcat.c_str(), pcat.length()); std::wstring lmessage(pmsg.c_str(), pmsg.length()); op::logging::instance().log_message(lcat, lmessage, (op::logging::loglevel)level); }
c++ method return string uses little bit technique:
java_bla_bla_bla_getname( jnienv *env, jclass operationclass, jlong handler ) { std::wstring retval = ... //.. code resolve std::wstring return env->newstring( (const jchar*)retval.c_str(), (jsize)retval.length()); }
Comments
Post a Comment