diff --git a/lib/src/main/cpp/libkiwix/library.cpp b/lib/src/main/cpp/libkiwix/library.cpp index cac6930..0eb04af 100644 --- a/lib/src/main/cpp/libkiwix/library.cpp +++ b/lib/src/main/cpp/libkiwix/library.cpp @@ -50,7 +50,7 @@ METHOD(jboolean, addBook, jobject book) } METHOD(jobject, getBookById, jstring id) { - return BUILD_WRAPPER("org/kiwix/libkiwix/Book", THIS->getBookById(TO_C(id))); + return BUILD_WRAPPER2("org/kiwix/libkiwix/Book", THIS->getBookById(TO_C(id))); } METHOD(jobject, getArchiveById, jstring id) { diff --git a/lib/src/main/cpp/utils.h b/lib/src/main/cpp/utils.h index 650ccd2..3f8ce91 100644 --- a/lib/src/main/cpp/utils.h +++ b/lib/src/main/cpp/utils.h @@ -60,6 +60,18 @@ inline jobject newObject(const char* className, JNIEnv* env) { } #define NEW_OBJECT(CLASSNAME) newObject(CLASSNAME, env) +// Create a java object using a constructor setting handle. +template +inline jobject newObject2(const char* className, JNIEnv* env, shared_ptr&& ptr) { + jclass objClass = env->FindClass(className); + jmethodID initMethod = env->GetMethodID(objClass, "", "(J)V"); + // allocate a shared_ptr on the head + shared_ptr* handle = new shared_ptr(ptr); + jobject wrapper = env->NewObject(objClass, initMethod, reinterpret_cast(handle)); + return wrapper; +} +#define NEW_OBJECT2(CLASSNAME, ptr) newObject2(CLASSNAME, env, ptr) + // Set the pointer to the wrapped object. template @@ -131,6 +143,15 @@ inline jobject buildWrapper(JNIEnv* env, const char* class_name, T&& obj, const } #define BUILD_WRAPPER(CLASSNAME, OBJ) buildWrapper(env, CLASSNAME, std::move(OBJ)) +template +inline jobject buildWrapper2(JNIEnv* env, const char* class_name, T&& obj, const char* handleName = "nativeHandle") { + auto ptr = std::make_shared(std::move(obj)); + auto wrapper = newObject2(class_name, env, std::move(ptr)); + return wrapper; +} +#define BUILD_WRAPPER2(CLASSNAME, OBJ) buildWrapper2(env, CLASSNAME, std::move(OBJ)) + + // --------------------------------------------------------------------------- diff --git a/lib/src/main/java/org/kiwix/libkiwix/Book.java b/lib/src/main/java/org/kiwix/libkiwix/Book.java index a7ddc88..d97d258 100644 --- a/lib/src/main/java/org/kiwix/libkiwix/Book.java +++ b/lib/src/main/java/org/kiwix/libkiwix/Book.java @@ -7,6 +7,9 @@ import org.kiwix.libkiwix.Illustration; public class Book { public Book() { allocate(); } + public Book(long handle) { + nativeHandle = handle; + } public native void update(Book book);