native-mate/native_mate/handle.h

73 строки
1.9 KiB
C
Исходник Обычный вид История

2014-04-15 07:04:36 +04:00
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE.chromium file.
#ifndef NATIVE_MATE_HANDLE_H_
#define NATIVE_MATE_HANDLE_H_
#include "native_mate/converter.h"
namespace mate {
// You can use mate::Handle on the stack to retain a mate::Wrappable object.
// Currently we don't have a mechanism for retaining a mate::Wrappable object
// in the C++ heap because strong references from C++ to V8 can cause memory
// leaks.
template<typename T>
class Handle {
public:
Handle() : object_(NULL) {}
2016-05-20 09:38:26 +03:00
Handle(v8::Local<v8::Object> wrapper, T* object)
2014-04-15 07:04:36 +04:00
: wrapper_(wrapper),
object_(object) {
}
bool IsEmpty() const { return !object_; }
void Clear() {
wrapper_.Clear();
object_ = NULL;
}
T* operator->() const { return object_; }
2016-05-20 09:38:26 +03:00
v8::Local<v8::Object> ToV8() const { return wrapper_; }
2014-04-15 07:04:36 +04:00
T* get() const { return object_; }
private:
2016-05-20 09:38:26 +03:00
v8::Local<v8::Object> wrapper_;
2014-04-15 07:04:36 +04:00
T* object_;
};
template<typename T>
struct Converter<mate::Handle<T> > {
2015-05-22 14:11:02 +03:00
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
2014-04-15 07:04:36 +04:00
const mate::Handle<T>& val) {
return val.ToV8();
}
2015-05-22 14:11:02 +03:00
static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
2014-04-15 07:04:36 +04:00
mate::Handle<T>* out) {
T* object = NULL;
if (val->IsNull() || val->IsUndefined()) {
*out = mate::Handle<T>();
return true;
}
2014-04-15 07:04:36 +04:00
if (!Converter<T*>::FromV8(isolate, val, &object)) {
return false;
}
2016-05-20 09:38:26 +03:00
*out = mate::Handle<T>(val->ToObject(), object);
2014-04-15 07:04:36 +04:00
return true;
}
};
// This function is a convenient way to create a handle from a raw pointer
// without having to write out the type of the object explicitly.
template<typename T>
mate::Handle<T> CreateHandle(v8::Isolate* isolate, T* object) {
2016-04-25 04:17:39 +03:00
return mate::Handle<T>(object->GetWrapper(), object);
2014-04-15 07:04:36 +04:00
}
} // namespace mate
#endif // NATIVE_MATE_HANDLE_H_