Turi Create  4.0
python_callbacks.hpp
1 /* Copyright © 2017 Apple Inc. All rights reserved.
2  *
3  * Use of this source code is governed by a BSD-3-clause license that can
4  * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
5  */
6 #ifndef TURI_PYTHON_CALLBACKS_H_
7 #define TURI_PYTHON_CALLBACKS_H_
8 
9 #include <core/util/code_optimization.hpp>
10 #include <string>
11 #include <core/export.hpp>
12 
13 /** Provides a generic interface to call cython functions (which can
14  * in turn call python functions) from the C++ code and properly
15  * handle exceptions.
16  */
17 
18 namespace turi { namespace python {
19 
20 struct python_exception_info {
21  std::string exception_pickle;
22  std::string exception_string;
23 };
24 
25 // Registers the exception
26 void register_python_exception(const python_exception_info*);
27 extern bool _python_exception_occured;
28 
29 void _process_registered_exception() GL_COLD_NOINLINE;
30 
31 /**
32  * Processes exceptions raised by the above functions. To use, do
33  *
34  * On the cython side:
35  *
36  * from cy_callbacks cipmort register_exception
37  *
38  * cdef void my_func(...):
39  * try:
40  * # Do stuff...
41  *
42  * except Exception, e:
43  * register_exception(e)
44  * return
45  *
46  *
47  * On the C++ side.
48  *
49  * cython_function_struct.my_func(...);
50  * check_for_python_exception();
51  */
52 static inline GL_HOT_INLINE void check_for_python_exception() {
53  if(UNLIKELY(_python_exception_occured)) {
54  _process_registered_exception();
55  }
56 }
57 
58 }}
59 
60 #endif /* TURI_PYTHON_CALLBACKS_H_ */
#define GL_HOT_INLINE