• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2025 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 ANI_UTIL_OBJECT_H
17 #define ANI_UTIL_OBJECT_H
18 
19 #include <ani.h>
20 #include <memory>
21 #include <string>
22 
23 class NativeObject {
24 public:
25     virtual ~NativeObject() = default;
26 };
27 
28 template <typename T>
29 class StdSharedPtrHolder : public NativeObject {
30 public:
StdSharedPtrHolder(const std::shared_ptr<T> & sptr)31     StdSharedPtrHolder(const std::shared_ptr<T> &sptr) : sptr_(sptr) {}
32 
Get()33     std::shared_ptr<T> Get()
34     {
35         return sptr_;
36     }
37 
GetOrDefault()38     std::shared_ptr<T> GetOrDefault()
39     {
40         if (!sptr_) {
41             sptr_ = std::make_shared<T>();
42         }
43         return sptr_;
44     }
45 
46 private:
47     std::shared_ptr<T> sptr_;
48 };
49 
50 class NativePtrCleaner {
51 public:
Clean(ani_env * env,ani_object object)52     static void Clean([[maybe_unused]] ani_env *env, [[maybe_unused]] ani_object object)
53     {
54         ani_long ptr = 0;
55         if (ANI_OK != env->Object_GetFieldByName_Long(object, "targetPtr", &ptr)) {
56             return;
57         }
58         delete reinterpret_cast<NativeObject *>(ptr);
59     }
60 
NativePtrCleaner(ani_env * env)61     NativePtrCleaner(ani_env *env) : env_(env) {}
62 
Bind(ani_class cls)63     ani_status Bind(ani_class cls)
64     {
65         std::array methods = {
66             ani_native_function {"clean", nullptr, reinterpret_cast<void *>(NativePtrCleaner::Clean)},
67         };
68 
69         if (ANI_OK != env_->Class_BindNativeMethods(cls, methods.data(), methods.size())) {
70             return (ani_status)ANI_ERROR;
71         };
72 
73         return ANI_OK;
74     }
75 
76 private:
77     ani_env *env_ = nullptr;
78 };
79 #endif
80