1 /** 2 * Copyright 2019 Huawei Technologies Co., Ltd 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #ifndef PYBIND_API_API_REGISTER_H_ 18 #define PYBIND_API_API_REGISTER_H_ 19 20 #include <map> 21 #include <string> 22 #include <memory> 23 #include <functional> 24 25 #include "pybind11/pybind11.h" 26 #include "pybind11/stl.h" 27 28 namespace py = pybind11; 29 30 namespace mindspore { 31 32 using PybindDefineFunc = std::function<void(py::module *)>; 33 34 class PybindDefineRegister { 35 public: Register(const std::string & name,const PybindDefineFunc & fn)36 static void Register(const std::string &name, const PybindDefineFunc &fn) { 37 return GetSingleton().RegisterFn(name, fn); 38 } 39 40 PybindDefineRegister(const PybindDefineRegister &) = delete; 41 42 PybindDefineRegister &operator=(const PybindDefineRegister &) = delete; 43 AllFuncs()44 static std::map<std::string, PybindDefineFunc> &AllFuncs() { return GetSingleton().fns_; } 45 46 std::map<std::string, PybindDefineFunc> fns_; 47 48 protected: 49 PybindDefineRegister() = default; 50 51 virtual ~PybindDefineRegister() = default; 52 53 static PybindDefineRegister &GetSingleton(); 54 RegisterFn(const std::string & name,const PybindDefineFunc & fn)55 void RegisterFn(const std::string &name, const PybindDefineFunc &fn) { fns_[name] = fn; } 56 }; 57 58 class PybindDefineRegisterer { 59 public: PybindDefineRegisterer(const std::string & name,const PybindDefineFunc & fn)60 PybindDefineRegisterer(const std::string &name, const PybindDefineFunc &fn) { 61 PybindDefineRegister::Register(name, fn); 62 } 63 ~PybindDefineRegisterer() = default; 64 }; 65 66 #define REGISTER_PYBIND_DEFINE(name, define) PybindDefineRegisterer g_pybind_define_f_##name(#name, define) 67 68 } // namespace mindspore 69 70 #endif // PYBIND_API_API_REGISTER_H_ 71