BatyaGG
BatyaGG

Reputation: 734

How to create native class using JNI?

I want to create C++ class with constructor and one method which returns string. My question is: how to initialize object of type "native class" in Java using C++ constructor and then from this Java object call native method?

Upvotes: 1

Views: 2247

Answers (1)

Alex Cohn
Alex Cohn

Reputation: 57203

There is no 'native class' in Java; we have 'native methods' that can be part of any Java class. The native methods are implemented as extern "C" functions.

In the nutshell, you can create in your Java two native methods, e.g. createNativeInstance and getNativeString. Note that you probably need another method to release the native instance:

#include <jni.h>

JNIEXPORT
jlong Java_test_createNativeInstance(JNIEnv *, jobject ) {
    return reinterpret_cast<jlong>(new CppClass());
}

JNIEXPORT
jstring Java_test_getNativeString(JNIEnv *env, jobject obj, jlong cppClassPtr) {
    CppClass* pCppClass = reinterpret_cast<CppClass*>(cppClassPtr);
    return env->NewStringUTF(env, pCppClass->getString();
}

JNIEXPORT
void Java_test_releaseNativeInstance(JNIEnv *env, jobject obj, jlong cppClassPtr) {
    CppClass* pCppClass = reinterpret_cast<CppClass*>(cppClassPtr);
    delete pCppClass;
}

The Java file test.java may look like:

public class test {
    public native long createNativeInstance();
    public native String getNativeString(long cppClassPtr);
    public native void releaseNativeInstance(long cppClassPtr);
}

Upvotes: 4

Related Questions