[go: nahoru, domu]

blob: d0fd583ea88d8e157e935d2598740cea1f1a7cf0 [file] [log] [blame]
Avi Drissman468e51b62022-09-13 20:47:011// Copyright 2013 The Chromium Authors
abarth@chromium.orgd379b0c2013-12-05 05:48:012// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef GIN_HANDLE_H_
6#define GIN_HANDLE_H_
7
Keishi Hattori0e45c022021-11-27 09:25:528#include "base/memory/raw_ptr.h"
abarth@chromium.orgd379b0c2013-12-05 05:48:019#include "gin/converter.h"
10
11namespace gin {
12
13// You can use gin::Handle on the stack to retain a gin::Wrappable object.
14// Currently we don't have a mechanism for retaining a gin::Wrappable object
15// in the C++ heap because strong references from C++ to V8 can cause memory
16// leaks.
17template<typename T>
18class Handle {
19 public:
Lukasz Anforowiczc695e532020-06-09 02:09:4520 Handle() : object_(nullptr) {}
abarth@chromium.orgd379b0c2013-12-05 05:48:0121
deepak.sfaaa1b62015-04-30 07:30:4822 Handle(v8::Local<v8::Value> wrapper, T* object)
abarth@chromium.orgd379b0c2013-12-05 05:48:0123 : wrapper_(wrapper),
24 object_(object) {
25 }
26
27 bool IsEmpty() const { return !object_; }
28
29 void Clear() {
30 wrapper_.Clear();
31 object_ = NULL;
32 }
33
34 T* operator->() const { return object_; }
deepak.sfaaa1b62015-04-30 07:30:4835 v8::Local<v8::Value> ToV8() const { return wrapper_; }
abarth@chromium.orgd379b0c2013-12-05 05:48:0136 T* get() const { return object_; }
37
38 private:
deepak.sfaaa1b62015-04-30 07:30:4839 v8::Local<v8::Value> wrapper_;
Keishi Hattori0e45c022021-11-27 09:25:5240 raw_ptr<T> object_;
abarth@chromium.orgd379b0c2013-12-05 05:48:0141};
42
43template<typename T>
44struct Converter<gin::Handle<T> > {
deepak.sfaaa1b62015-04-30 07:30:4845 static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
abarth@chromium.orgd379b0c2013-12-05 05:48:0146 const gin::Handle<T>& val) {
47 return val.ToV8();
48 }
deepak.sfaaa1b62015-04-30 07:30:4849 static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
abarth@chromium.orgd379b0c2013-12-05 05:48:0150 gin::Handle<T>* out) {
51 T* object = NULL;
aa@chromium.org481d2492013-12-13 23:55:2552 if (!Converter<T*>::FromV8(isolate, val, &object)) {
53 return false;
54 }
55 *out = gin::Handle<T>(val, object);
56 return true;
abarth@chromium.orgd379b0c2013-12-05 05:48:0157 }
58};
59
60// This function is a convenient way to create a handle from a raw pointer
61// without having to write out the type of the object explicitly.
62template<typename T>
63gin::Handle<T> CreateHandle(v8::Isolate* isolate, T* object) {
Ken Rockot2b0f07652017-04-12 19:10:4964 v8::Local<v8::Object> wrapper;
65 if (!object->GetWrapper(isolate).ToLocal(&wrapper) || wrapper.IsEmpty())
hajimehoshi@chromium.orge0719edc2014-02-28 14:48:2566 return gin::Handle<T>();
67 return gin::Handle<T>(wrapper, object);
abarth@chromium.orgd379b0c2013-12-05 05:48:0168}
69
70} // namespace gin
71
72#endif // GIN_HANDLE_H_