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 INTERFACES_KITS_JS_SRC_COMMON_ANI_HELPER_BIND_FUNCTION_H
17 #define INTERFACES_KITS_JS_SRC_COMMON_ANI_HELPER_BIND_FUNCTION_H
18
19 #include <vector>
20 #include <ani.h>
21 #include "filemgmt_libhilog.h"
22
23 namespace OHOS {
24 namespace FileManagement {
25 namespace ModuleFileIO {
26 namespace ANI {
27
28 template <std::size_t N>
BindClass(ani_env * env,const char * className,const std::array<ani_native_function,N> & methods)29 ANI_EXPORT ani_status BindClass(ani_env *env, const char *className, const std::array<ani_native_function, N> &methods)
30 {
31 if (env == nullptr) {
32 HILOGE("Invalid parameter env");
33 return ANI_INVALID_ARGS;
34 }
35
36 if (className == nullptr) {
37 HILOGE("Invalid parameter className");
38 return ANI_INVALID_ARGS;
39 }
40
41 ani_class cls;
42 if (ANI_OK != env->FindClass(className, &cls)) {
43 HILOGE("Cannot find class '%{private}s'", className);
44 return ANI_NOT_FOUND;
45 }
46
47 if (ANI_OK != env->Class_BindNativeMethods(cls, methods.data(), methods.size())) {
48 HILOGE("Cannot bind native methods to '%{private}s'", className);
49 return ANI_ERROR;
50 };
51 return ANI_OK;
52 }
53
54 template <std::size_t N>
BindNamespace(ani_env * env,const char * namespaceStr,const std::array<ani_native_function,N> & methods)55 ANI_EXPORT ani_status BindNamespace(
56 ani_env *env, const char *namespaceStr, const std::array<ani_native_function, N> &methods)
57 {
58 if (env == nullptr) {
59 HILOGE("Invalid parameter env");
60 return ANI_INVALID_ARGS;
61 }
62
63 if (namespaceStr == nullptr) {
64 HILOGE("Invalid parameter namespaceStr");
65 return ANI_INVALID_ARGS;
66 }
67
68 ani_namespace ns;
69 if (ANI_OK != env->FindNamespace(namespaceStr, &ns)) {
70 HILOGE("Cannot find namespace '%{private}s'", namespaceStr);
71 return ANI_NOT_FOUND;
72 }
73
74 if (ANI_OK != env->Namespace_BindNativeFunctions(ns, methods.data(), methods.size())) {
75 HILOGE("Cannot bind native methods to '%{private}s'", namespaceStr);
76 return ANI_ERROR;
77 };
78 return ANI_OK;
79 }
80
81 } // namespace ANI
82 } // namespace ModuleFileIO
83 } // namespace FileManagement
84 } // namespace OHOS
85
86 #endif // INTERFACES_KITS_JS_SRC_COMMON_ANI_HELPER_BIND_FUNCTION_H