lime
Lime is a C++ library implementing Open Whisper System Signal protocol
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 
6 namespace 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  }
Definition: weak_reference.hpp:8
decltype(Untag(std::declval< T >())) UntaggedType
Definition: tagging.hpp:130
Definition: weak_reference.hpp:15
Definition: ownership.hpp:26
Definition: object.hpp:44
Definition: advanced_ownership.hpp:5
static const Class & Singleton(JNIEnv &env)
Definition: class.hpp:101
WeakReference(JNIEnv &env, const T &referent)
Definition: weak_reference.hpp:21
Definition: unique.hpp:38
static constexpr auto Name()
Definition: weak_reference.hpp:8
UntaggedType * release()
Definition: unique.hpp:89