1 /*
2  * Copyright (c) 2024 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 OHOS_FFI_CJ_FN_INVOKER_H
17 #define OHOS_FFI_CJ_FN_INVOKER_H
18 
19 #include <cstdint>
20 #include <string>
21 
22 #include "nocopyable.h"
23 
24 #ifndef FFI_EXPORT
25 #ifndef WINDOWS_PLATFORM
26 #define FFI_EXPORT __attribute__((visibility("default")))
27 #else
28 #define FFI_EXPORT __declspec(dllexport)
29 #endif
30 #endif
31 
32 extern "C" {
33 struct FFIAtCPackage {
34     void (*atCOHOSFFICJThrow)(const char* msg) = nullptr;
35     bool (*atCOHOSFFIExistFFIDataExist)(int64_t id) = nullptr;
36     bool (*atCOHOSFFIReleaseFFIData)(int64_t id) = nullptr;
37     bool (*atCOHOSFFIReleaseRemoteData)(int64_t id) = nullptr;
38     void (*atCOHOSFFICallbackInvoker)(int64_t lambdaId, int32_t argc, void** argv, void* res) = nullptr;
39 };
40 }
41 
42 class FFI_EXPORT CJFFIFnInvoker {
43 public:
44     DISALLOW_COPY_AND_MOVE(CJFFIFnInvoker);
45     static CJFFIFnInvoker* GetInstance();
46 
RegisterCJFuncs(FFIAtCPackage funcs)47     void RegisterCJFuncs(FFIAtCPackage funcs)
48     {
49         cjFFIFn_ = funcs;
50         fnLoaded_ = true;
51     }
52 
53     const FFIAtCPackage& GetCJFuncs();
54 
CJFuncsLoaded()55     bool CJFuncsLoaded() const
56     {
57         return fnLoaded_;
58     }
59 
60     bool FFIDataExist(int64_t id) const;
61     bool ReleaseFFIData(int64_t id) const;
62     bool ReleaseRemoteData(int64_t id) const;
63     void ThrowCJError(const std::string& msg) const;
64     void InvokeLambda(int64_t lambdaId, int32_t argc, void** argv, void* result) const;
65 
66 private:
67     CJFFIFnInvoker() = default;
68     bool fnLoaded_ = false;
69     FFIAtCPackage cjFFIFn_;
70 };
71 
72 #endif // OHOS_FFI_CJ_FN_INVOKER_H
73