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

[Question] How to wrap native function returning string using HighLevelWrapper

Open Szaq opened this issue 7 years ago • 1 comments

As in

JNIEXPORT jstring JNICALL
Java_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env,
                                                  jobject thiz ) {
    return env->NewStringUTF("Hello from JNI !Compiled.");
}

Due to various incarnations of deleted constructor of jni::Object<jni::StringTag> I don't know how to make it compile.

Szaq avatar Jan 27 '19 16:01 Szaq

Not a maintainer or contributor, but I've been working with this library a bit lately. Here's a simple gist which shows how to register a static native method to a java class method. For 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 );

The high-level API is all about the tags, which are defined in the public const char* method Name(). All that makes jni::String special is literally this:

struct StringTag
{
    static constexpr auto Name() { return "java/lang/String"; }
};

In the high level API, jni::Class, jni::Object, and jni::Field are generally passed by reference, and are wrapped in Local<> or Global<> ownership types which both derive from jni::Unique. They cannot be copy-constructed, and need to be constructed via one of the static methods (jni::Class::Find( env ) for example) or with jni::NewLocal or jni::NewGlobal. The deleted constructor error occurs when you try to directly create jni::Object, while you should be creating a reference to that object.

Start with the Readme, then look at examples/native_peer.cpp. This should help you get started. The NativePeer example is an invaluable use case, it solves and neatly hides pointer to member function registration. Finally, I found the most help in test/high_level.cpp - this lays out all the syntax you need for almost everything.

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