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 #ifndef ABILITY_RUNTIME_BINDABLE_H 17 #define ABILITY_RUNTIME_BINDABLE_H 18 19 #include <memory> 20 21 namespace OHOS { 22 namespace AbilityRuntime { 23 class Runtime; 24 25 class BindingObject final { 26 public: 27 template<class T> BindingObject(Runtime & runtime,T * ptr)28 BindingObject(Runtime& runtime, T* ptr) : runtime_(runtime), object_(ptr, SimpleRelease<T>) {} 29 ~BindingObject() = default; 30 31 template<class T> Get()32 T* Get() 33 { 34 return static_cast<T*>(object_.get()); 35 } 36 Reset()37 void Reset() 38 { 39 object_.reset(); 40 } 41 GetRuntime()42 Runtime& GetRuntime() 43 { 44 return runtime_; 45 } 46 47 BindingObject(const BindingObject&) = delete; 48 BindingObject& operator=(const BindingObject&) = delete; 49 BindingObject(BindingObject&&) = delete; 50 BindingObject& operator=(BindingObject&&) = delete; 51 52 private: 53 template<class T> SimpleRelease(void * ptr)54 static void SimpleRelease(void* ptr) 55 { 56 delete static_cast<T*>(ptr); 57 } 58 59 Runtime& runtime_; 60 std::unique_ptr<void, void(*)(void*)> object_; 61 }; 62 63 class Bindable { 64 public: 65 virtual ~Bindable() = default; 66 67 template<class T> Bind(Runtime & runtime,T * object)68 void Bind(Runtime& runtime, T* object) 69 { 70 object_ = std::make_unique<BindingObject>(runtime, object); 71 } 72 GetBindingObject()73 const std::unique_ptr<BindingObject>& GetBindingObject() const 74 { 75 return object_; 76 } 77 78 protected: 79 Bindable() = default; 80 81 private: 82 std::unique_ptr<BindingObject> object_; 83 }; 84 } // namespace AbilityRuntime 85 } // namespace OHOS 86 #endif // ABILITY_RUNTIME_BINDABLE_H