Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can use <a href="http://en.cppreference.com/w/cpp/memory/unique_ptr" rel="noreferrer"><code>std::unique_ptr</code></a> in C++11, which allows you to set the deleter yourself:</p> <pre><code>#include &lt;memory&gt; #include &lt;functional&gt; typedef std::unique_ptr&lt;char const[], std::function&lt;void(char const*)&gt;&gt; jni_string_ptr; // the "std::function" is needed to store any callable† extern "C" JNIEXPORT void JNICALL Java_ClassName_MethodName (JNIEnv *env, jobject obj, jstring javaString) { //Get the native string from javaString jni_string_ptr nativeString(env-&gt;GetStringUTFChars(javaString, 0), [=](char const* p) mutable{ env-&gt;ReleaseStringUTFChars(javaString, p); }); // lambda as the deleter // mutable needed if "ReleaseStringUTFChars" is a non-const method //Do something with the nativeString // nativeString automatically calls the passed deleter } </code></pre> <p>If you're stuck in C++03 and don't have access to <code>std::unique_ptr</code>, <a href="http://www.boost.org/libs/smart_ptr/shared_ptr.htm" rel="noreferrer"><code>boost::shared_array</code></a> provides a.. <em>viable</em> alternative.</p> <pre><code>#include &lt;boost/shared_ptr.hpp&gt; typedef boost::shared_array&lt;char const*&gt; jni_string_ptr; struct jni_string_deleter{ jni_string_deleter(JNIEnv* e, jstring js) : _env(e), _java_string(js) {} void operator()(char const* p) const{ _env-&gt;ReleaseStringUTFChars(_java_string, p); } private: JNIEnv* _env; jstring _java_string; }; extern "C" JNIEXPORT void JNICALL Java_ClassName_MethodName (JNIEnv *env, jobject obj, jstring javaString) { //Get the native string from javaString jni_string_ptr nativeString(env-&gt;GetStringUTFChars(javaString, 0), jni_string_deleter(env, javaString)); //Do something with the nativeString // nativeString automatically calls the passed deleter } </code></pre> <hr> <p>† You can also use a specific delter type here, as with the <code>shared_array</code> example, to avoid the type-erasure overhead of <code>std::function</code>:</p> <pre><code>struct jni_string_deleter{ jni_string_deleter(JNIEnv* e, jstring js) : _env(e), _java_string(js) {} void operator()(char const* p) const{ _env-&gt;ReleaseStringUTFChars(_java_string, p); } private: JNIEnv* _env; jstring _java_string; }; typedef std::unique_ptr&lt;char const[], jni_string_deleter&gt; jni_string_ptr; // create jni_string_ptr(env-&gt;get_the_chars(), jni_string_deleter(env, javaString)); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload