lime
Lime is a C++ library implementing Open Whisper System Signal protocol
Loading...
Searching...
No Matches
weak_reference.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <jni/class.hpp>
4#include <jni/object.hpp>
5
6namespace jni
7 {
8 struct WeakReferenceTag { static constexpr auto Name() { return "java/lang/ref/WeakReference"; } };
9
10 // Wraps a JNI global reference to a java.lang.ref.WeakReference, producing an ownership class
11 // similar to jni::Weak<T> (JNI's weak global reference), but with more reliable promotion semantics.
12 // Whereas a JNI weak global reference may still be promoted to a strong reference even during
13 // finalization, leading to potential use-after-free errors, a WeakReference cannot.
14 template < class T, template < RefDeletionMethod > class Deleter = DefaultRefDeleter >
16 {
17 private:
18 Global<Object<WeakReferenceTag>, Deleter> reference;
19
20 public:
21 WeakReference(JNIEnv& env, const T& referent)
22 {
23 static auto& klass = Class<WeakReferenceTag>::Singleton(env);
24 static auto constructor = klass.GetConstructor<Object<>>(env);
25 reference = NewGlobal<Deleter>(env, klass.New(env, constructor, referent));
26 }
27
28 Local<T> get(JNIEnv& env)
29 {
30 if (!reference)
31 {
32 return Local<T>();
33 }
34
35 static auto& klass = Class<WeakReferenceTag>::Singleton(env);
36 static auto get = klass.template GetMethod<Object<> ()>(env, "get");
37 return Local<T>(env, reinterpret_cast<typename T::UntaggedType*>(reference.Call(env, get).release()));
38 }
39 };
40 }
static const Class & Singleton(JNIEnv &env)
Definition class.hpp:101
Definition ownership.hpp:27
Definition object.hpp:45
Local< T > get(JNIEnv &env)
Definition weak_reference.hpp:28
WeakReference(JNIEnv &env, const T &referent)
Definition weak_reference.hpp:21
Definition advanced_ownership.hpp:6
Unique< T, Deleter<&JNIEnv::DeleteGlobalRef > > Global
Definition unique.hpp:102
auto NewGlobal(JNIEnv &env, const T &t)
Definition unique.hpp:156
Unique< T, DefaultRefDeleter<&JNIEnv::DeleteLocalRef > > Local
Definition unique.hpp:110
Definition weak_reference.hpp:8
static constexpr auto Name()
Definition weak_reference.hpp:8