#include "FunctionReference.h" #include "Caches.h" #include "ObjectManager.h" #include "Helpers.h" #include "Constants.h" using namespace v8; namespace tns { void FunctionReference::Register(Local context, Local interop) { Isolate* isolate = context->GetIsolate(); Local ctorFunc = FunctionReference::GetFunctionReferenceCtorFunc(context); bool success = interop->Set(context, tns::ToV8String(isolate, "FunctionReference"), ctorFunc).FromMaybe(false); tns::Assert(success, isolate); } Local FunctionReference::GetFunctionReferenceCtorFunc(Local context) { Isolate* isolate = context->GetIsolate(); auto cache = Caches::Get(isolate); Persistent* poFunctionReferenceCtor = cache->FunctionReferenceCtorFunc.get(); if (poFunctionReferenceCtor != nullptr) { return poFunctionReferenceCtor->Get(isolate); } Local ctorFuncTemplate = FunctionTemplate::New(isolate, FunctionReferenceConstructorCallback); ctorFuncTemplate->InstanceTemplate()->SetInternalFieldCount(1); ctorFuncTemplate->SetClassName(tns::ToV8String(isolate, "FunctionReference")); Local ctorFunc; if (!ctorFuncTemplate->GetFunction(context).ToLocal(&ctorFunc)) { tns::Assert(false, isolate); } tns::SetValue(isolate, ctorFunc, MakeGarbageCollected(isolate)); cache->FunctionReferenceCtorFunc = std::make_unique>(isolate, ctorFunc); cache->FunctionReferenceCtorFunc->SetWrapperClassId(Constants::ClassTypes::DataWrapper); return ctorFunc; } void FunctionReference::FunctionReferenceConstructorCallback(const FunctionCallbackInfo& info) { Isolate* isolate = info.GetIsolate(); Local context = isolate->GetCurrentContext(); tns::Assert(info.Length() == 1, isolate); tns::Assert(info[0]->IsFunction(), isolate); Local arg = info[0].As(); std::shared_ptr> poArg = ObjectManager::Register(context, arg); FunctionReferenceWrapper* wrapper = MakeGarbageCollected(isolate, poArg); tns::SetValue(isolate, arg, wrapper); info.GetReturnValue().Set(arg); } }