handle.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2013 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef GIN_HANDLE_H_
  5. #define GIN_HANDLE_H_
  6. #include "base/memory/raw_ptr.h"
  7. #include "gin/converter.h"
  8. namespace gin {
  9. // You can use gin::Handle on the stack to retain a gin::Wrappable object.
  10. // Currently we don't have a mechanism for retaining a gin::Wrappable object
  11. // in the C++ heap because strong references from C++ to V8 can cause memory
  12. // leaks.
  13. template<typename T>
  14. class Handle {
  15. public:
  16. Handle() : object_(nullptr) {}
  17. Handle(v8::Local<v8::Value> wrapper, T* object)
  18. : wrapper_(wrapper),
  19. object_(object) {
  20. }
  21. bool IsEmpty() const { return !object_; }
  22. void Clear() {
  23. wrapper_.Clear();
  24. object_ = NULL;
  25. }
  26. T* operator->() const { return object_; }
  27. v8::Local<v8::Value> ToV8() const { return wrapper_; }
  28. T* get() const { return object_; }
  29. private:
  30. v8::Local<v8::Value> wrapper_;
  31. raw_ptr<T> object_;
  32. };
  33. template<typename T>
  34. struct Converter<gin::Handle<T> > {
  35. static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
  36. const gin::Handle<T>& val) {
  37. return val.ToV8();
  38. }
  39. static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
  40. gin::Handle<T>* out) {
  41. T* object = NULL;
  42. if (!Converter<T*>::FromV8(isolate, val, &object)) {
  43. return false;
  44. }
  45. *out = gin::Handle<T>(val, object);
  46. return true;
  47. }
  48. };
  49. // This function is a convenient way to create a handle from a raw pointer
  50. // without having to write out the type of the object explicitly.
  51. template<typename T>
  52. gin::Handle<T> CreateHandle(v8::Isolate* isolate, T* object) {
  53. v8::Local<v8::Object> wrapper;
  54. if (!object->GetWrapper(isolate).ToLocal(&wrapper) || wrapper.IsEmpty())
  55. return gin::Handle<T>();
  56. return gin::Handle<T>(wrapper, object);
  57. }
  58. } // namespace gin
  59. #endif // GIN_HANDLE_H_