1 /*
2 * Copyright (c) 2021 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "quickjs_native_external.h"
17
QuickJSNativeExternal(QuickJSNativeEngine * engine,void * value,NativeFinalize callback,void * hint)18 QuickJSNativeExternal::QuickJSNativeExternal(QuickJSNativeEngine* engine,
19 void* value,
20 NativeFinalize callback,
21 void* hint)
22 : QuickJSNativeValue(engine, JS_UNDEFINED)
23 {
24 NativeObjectInfo* info = NativeObjectInfo::CreateNewInstance();
25 if (info != nullptr) {
26 info->engine = engine;
27 info->nativeObject = value;
28 info->callback = callback;
29 info->hint = hint;
30 }
31
32 value_ = JS_NewExternal(
33 engine->GetContext(), info,
34 [](JSContext* context, void* data, void* hint) {
35 auto info = reinterpret_cast<NativeObjectInfo*>(data);
36 if (info != nullptr) {
37 info->callback(info->engine, info->nativeObject, info->hint);
38 delete info;
39 }
40 },
41 nullptr);
42 }
43
QuickJSNativeExternal(QuickJSNativeEngine * engine,JSValue value)44 QuickJSNativeExternal::QuickJSNativeExternal(QuickJSNativeEngine* engine, JSValue value)
45 : QuickJSNativeValue(engine, value)
46 {
47 }
48
~QuickJSNativeExternal()49 QuickJSNativeExternal::~QuickJSNativeExternal() {}
50
GetInterface(int interfaceId)51 void* QuickJSNativeExternal::GetInterface(int interfaceId)
52 {
53 return (NativeExternal::INTERFACE_ID == interfaceId) ? (NativeExternal*)this : nullptr;
54 }
55
operator void*()56 QuickJSNativeExternal::operator void*()
57 {
58 NativeObjectInfo* info = (NativeObjectInfo*)JS_ExternalToNativeObject(engine_->GetContext(), value_);
59 return (info != nullptr) ? info->nativeObject : nullptr;
60 }