jni.hpp icon indicating copy to clipboard operation
jni.hpp copied to clipboard

How can I use the library to expose a native method taking std::string?

Open haelix888 opened this issue 6 years ago • 1 comments

Or otherwise said, do I expect of the library to "wrap"/generate marshalling code (and if so, to which extent?), or should I declare my native methods to take something as close as possible to the Java types? In this case, jstring. But that fails like:

/mnt/data/dev/mapbox-jnihpp/include/jni/tagging.hpp:130:40:   required by substitution of ‘template<class T> using UntaggedType = decltype (jni::Untag(declval<T>())) [with T = jni::jstring]’
/mnt/data/dev/mapbox-jnihpp/include/jni/tagging.hpp:124:64: error: ‘const struct jni::jstring’ has no member named ‘get’

haelix888 avatar Nov 22 '18 15:11 haelix888

For marshaling strings, the methods you want to know are:

const char* c_str = "Hello World";
std::string std_str( c_str );
jni::Local<jni::String> c_string_to_java_string = jni::Make<jni::String>( env, c_str );
jni::Local<jni::String> std_string_to_java_string = jni::Make<jni::String>( env, std_str );
std::string std_str_from_java_string = jni::Make<std::string>( env, c_string_to_java_string );

Use jni::Local<jni::String> in place of jstring for both java->native and native->Java methods.

The standard types - jni::jstring, jni::jobject, etc are part of the low-level API. You can use them, but for methods taking Unique<T> parameters you'll need to create an ownership type wrapper first, see jni::NewLocal.

this-kirke avatar Feb 16 '19 12:02 this-kirke