Loading...
Searching...
No Matches
weak_reference.hpp
Go to the documentation of this file.
#pragma once
#include <jni/class.hpp>
#include <jni/object.hpp>
namespace jni
{
struct WeakReferenceTag { static constexpr auto Name() { return "java/lang/ref/WeakReference"; } };
// Wraps a JNI global reference to a java.lang.ref.WeakReference, producing an ownership class
// similar to jni::Weak<T> (JNI's weak global reference), but with more reliable promotion semantics.
// Whereas a JNI weak global reference may still be promoted to a strong reference even during
// finalization, leading to potential use-after-free errors, a WeakReference cannot.
template < class T, template < RefDeletionMethod > class Deleter = DefaultRefDeleter >
class WeakReference
{
private:
Global<Object<WeakReferenceTag>, Deleter> reference;
public:
WeakReference(JNIEnv& env, const T& referent)
{
static auto& klass = Class<WeakReferenceTag>::Singleton(env);
static auto constructor = klass.GetConstructor<Object<>>(env);
reference = NewGlobal<Deleter>(env, klass.New(env, constructor, referent));
}
Local<T> get(JNIEnv& env)
{
if (!reference)
{
return Local<T>();
}
static auto& klass = Class<WeakReferenceTag>::Singleton(env);
static auto get = klass.template GetMethod<Object<> ()>(env, "get");
return Local<T>(env, reinterpret_cast<typename T::UntaggedType*>(reference.Call(env, get).release()));
}
};
}
class.hpp
jni::Class::Singleton
static const Class & Singleton(JNIEnv &env)
Definition class.hpp:101
jni::DefaultRefDeleter
Definition ownership.hpp:27
jni::Object
Definition object.hpp:45
jni::WeakReference::get
Local< T > get(JNIEnv &env)
Definition weak_reference.hpp:28
jni::WeakReference::WeakReference
WeakReference(JNIEnv &env, const T &referent)
Definition weak_reference.hpp:21
jni
Definition advanced_ownership.hpp:6
jni::Global
Unique< T, Deleter<&JNIEnv::DeleteGlobalRef > > Global
Definition unique.hpp:102
jni::NewGlobal
auto NewGlobal(JNIEnv &env, const T &t)
Definition unique.hpp:156
jni::Local
Unique< T, DefaultRefDeleter<&JNIEnv::DeleteLocalRef > > Local
Definition unique.hpp:110
object.hpp
jni::WeakReferenceTag
Definition weak_reference.hpp:8
jni::WeakReferenceTag::Name
static constexpr auto Name()
Definition weak_reference.hpp:8