ctpbee-opt-api 0.1.0__cp310-cp310-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (414) hide show
  1. ctpbee_api/__init__.py +17 -0
  2. ctpbee_api/ctp/__init__.py +3 -0
  3. ctpbee_api/ctp/ctp_constant.py +1253 -0
  4. ctpbee_api/ctp/generator/concat.py +93 -0
  5. ctpbee_api/ctp/generator/const.py +325 -0
  6. ctpbee_api/ctp/generator/ctp_constant.py +1274 -0
  7. ctpbee_api/ctp/generator/ctp_md_header_define.h +13 -0
  8. ctpbee_api/ctp/generator/ctp_md_header_function.h +6 -0
  9. ctpbee_api/ctp/generator/ctp_md_header_on.h +26 -0
  10. ctpbee_api/ctp/generator/ctp_md_header_process.h +26 -0
  11. ctpbee_api/ctp/generator/ctp_md_source_function.cpp +42 -0
  12. ctpbee_api/ctp/generator/ctp_md_source_module.cpp +18 -0
  13. ctpbee_api/ctp/generator/ctp_md_source_on.cpp +156 -0
  14. ctpbee_api/ctp/generator/ctp_md_source_process.cpp +282 -0
  15. ctpbee_api/ctp/generator/ctp_md_source_switch.cpp +78 -0
  16. ctpbee_api/ctp/generator/ctp_md_source_task.cpp +211 -0
  17. ctpbee_api/ctp/generator/ctp_struct.py +5640 -0
  18. ctpbee_api/ctp/generator/ctp_td_header_define.h +130 -0
  19. ctpbee_api/ctp/generator/ctp_td_header_function.h +174 -0
  20. ctpbee_api/ctp/generator/ctp_td_header_on.h +260 -0
  21. ctpbee_api/ctp/generator/ctp_td_header_process.h +260 -0
  22. ctpbee_api/ctp/generator/ctp_td_source_function.cpp +1456 -0
  23. ctpbee_api/ctp/generator/ctp_td_source_module.cpp +222 -0
  24. ctpbee_api/ctp/generator/ctp_td_source_on.cpp +1572 -0
  25. ctpbee_api/ctp/generator/ctp_td_source_process.cpp +5472 -0
  26. ctpbee_api/ctp/generator/ctp_td_source_switch.cpp +780 -0
  27. ctpbee_api/ctp/generator/ctp_td_source_task.cpp +2444 -0
  28. ctpbee_api/ctp/generator/ctp_typedef.py +800 -0
  29. ctpbee_api/ctp/generator/generate_api_functions.py +345 -0
  30. ctpbee_api/ctp/generator/generate_data_type.py +76 -0
  31. ctpbee_api/ctp/generator/generate_struct.py +84 -0
  32. ctpbee_api/ctp/include/mac/ctp/ThostFtdcMdApi.h +168 -0
  33. ctpbee_api/ctp/include/mac/ctp/ThostFtdcTraderApi.h +770 -0
  34. ctpbee_api/ctp/include/mac/ctp/ThostFtdcUserApiDataType.h +6878 -0
  35. ctpbee_api/ctp/include/mac/ctp/ThostFtdcUserApiStruct.h +10915 -0
  36. ctpbee_api/ctp/include/mac/pybind11/attr.h +690 -0
  37. ctpbee_api/ctp/include/mac/pybind11/buffer_info.h +208 -0
  38. ctpbee_api/ctp/include/mac/pybind11/cast.h +1704 -0
  39. ctpbee_api/ctp/include/mac/pybind11/chrono.h +225 -0
  40. ctpbee_api/ctp/include/mac/pybind11/common.h +2 -0
  41. ctpbee_api/ctp/include/mac/pybind11/complex.h +74 -0
  42. ctpbee_api/ctp/include/mac/pybind11/detail/class.h +743 -0
  43. ctpbee_api/ctp/include/mac/pybind11/detail/common.h +1255 -0
  44. ctpbee_api/ctp/include/mac/pybind11/detail/descr.h +171 -0
  45. ctpbee_api/ctp/include/mac/pybind11/detail/init.h +434 -0
  46. ctpbee_api/ctp/include/mac/pybind11/detail/internals.h +656 -0
  47. ctpbee_api/ctp/include/mac/pybind11/detail/type_caster_base.h +1177 -0
  48. ctpbee_api/ctp/include/mac/pybind11/detail/typeid.h +65 -0
  49. ctpbee_api/ctp/include/mac/pybind11/eigen/common.h +9 -0
  50. ctpbee_api/ctp/include/mac/pybind11/eigen/matrix.h +714 -0
  51. ctpbee_api/ctp/include/mac/pybind11/eigen/tensor.h +516 -0
  52. ctpbee_api/ctp/include/mac/pybind11/eigen.h +12 -0
  53. ctpbee_api/ctp/include/mac/pybind11/embed.h +316 -0
  54. ctpbee_api/ctp/include/mac/pybind11/eval.h +156 -0
  55. ctpbee_api/ctp/include/mac/pybind11/functional.h +137 -0
  56. ctpbee_api/ctp/include/mac/pybind11/gil.h +239 -0
  57. ctpbee_api/ctp/include/mac/pybind11/iostream.h +265 -0
  58. ctpbee_api/ctp/include/mac/pybind11/numpy.h +1998 -0
  59. ctpbee_api/ctp/include/mac/pybind11/operators.h +202 -0
  60. ctpbee_api/ctp/include/mac/pybind11/options.h +92 -0
  61. ctpbee_api/ctp/include/mac/pybind11/pybind11.h +2890 -0
  62. ctpbee_api/ctp/include/mac/pybind11/pytypes.h +2557 -0
  63. ctpbee_api/ctp/include/mac/pybind11/stl/filesystem.h +116 -0
  64. ctpbee_api/ctp/include/mac/pybind11/stl.h +447 -0
  65. ctpbee_api/ctp/include/mac/pybind11/stl_bind.h +851 -0
  66. ctpbee_api/ctp/include/mac/pybind11/type_caster_pyobject_ptr.h +61 -0
  67. ctpbee_api/ctp/include/new/ctp/ThostFtdcMdApi.h +168 -0
  68. ctpbee_api/ctp/include/new/ctp/ThostFtdcTraderApi.h +770 -0
  69. ctpbee_api/ctp/include/new/ctp/ThostFtdcUserApiDataType.h +6878 -0
  70. ctpbee_api/ctp/include/new/ctp/ThostFtdcUserApiStruct.h +10915 -0
  71. ctpbee_api/ctp/include/new/pybind11/attr.h +690 -0
  72. ctpbee_api/ctp/include/new/pybind11/buffer_info.h +208 -0
  73. ctpbee_api/ctp/include/new/pybind11/cast.h +1704 -0
  74. ctpbee_api/ctp/include/new/pybind11/chrono.h +225 -0
  75. ctpbee_api/ctp/include/new/pybind11/common.h +2 -0
  76. ctpbee_api/ctp/include/new/pybind11/complex.h +74 -0
  77. ctpbee_api/ctp/include/new/pybind11/detail/class.h +743 -0
  78. ctpbee_api/ctp/include/new/pybind11/detail/common.h +1255 -0
  79. ctpbee_api/ctp/include/new/pybind11/detail/descr.h +171 -0
  80. ctpbee_api/ctp/include/new/pybind11/detail/init.h +434 -0
  81. ctpbee_api/ctp/include/new/pybind11/detail/internals.h +656 -0
  82. ctpbee_api/ctp/include/new/pybind11/detail/type_caster_base.h +1177 -0
  83. ctpbee_api/ctp/include/new/pybind11/detail/typeid.h +65 -0
  84. ctpbee_api/ctp/include/new/pybind11/eigen/common.h +9 -0
  85. ctpbee_api/ctp/include/new/pybind11/eigen/matrix.h +714 -0
  86. ctpbee_api/ctp/include/new/pybind11/eigen/tensor.h +516 -0
  87. ctpbee_api/ctp/include/new/pybind11/eigen.h +12 -0
  88. ctpbee_api/ctp/include/new/pybind11/embed.h +316 -0
  89. ctpbee_api/ctp/include/new/pybind11/eval.h +156 -0
  90. ctpbee_api/ctp/include/new/pybind11/functional.h +137 -0
  91. ctpbee_api/ctp/include/new/pybind11/gil.h +239 -0
  92. ctpbee_api/ctp/include/new/pybind11/iostream.h +265 -0
  93. ctpbee_api/ctp/include/new/pybind11/numpy.h +1998 -0
  94. ctpbee_api/ctp/include/new/pybind11/operators.h +202 -0
  95. ctpbee_api/ctp/include/new/pybind11/options.h +92 -0
  96. ctpbee_api/ctp/include/new/pybind11/pybind11.h +2890 -0
  97. ctpbee_api/ctp/include/new/pybind11/pytypes.h +2557 -0
  98. ctpbee_api/ctp/include/new/pybind11/stl/filesystem.h +116 -0
  99. ctpbee_api/ctp/include/new/pybind11/stl.h +447 -0
  100. ctpbee_api/ctp/include/new/pybind11/stl_bind.h +851 -0
  101. ctpbee_api/ctp/include/new/pybind11/type_caster_pyobject_ptr.h +61 -0
  102. ctpbee_api/ctp/include/previous/ctp/ThostFtdcMdApi.h +168 -0
  103. ctpbee_api/ctp/include/previous/ctp/ThostFtdcTraderApi.h +770 -0
  104. ctpbee_api/ctp/include/previous/ctp/ThostFtdcUserApiDataType.h +6878 -0
  105. ctpbee_api/ctp/include/previous/ctp/ThostFtdcUserApiStruct.h +10915 -0
  106. ctpbee_api/ctp/include/previous/pybind11/attr.h +489 -0
  107. ctpbee_api/ctp/include/previous/pybind11/buffer_info.h +108 -0
  108. ctpbee_api/ctp/include/previous/pybind11/cast.h +2067 -0
  109. ctpbee_api/ctp/include/previous/pybind11/chrono.h +162 -0
  110. ctpbee_api/ctp/include/previous/pybind11/common.h +2 -0
  111. ctpbee_api/ctp/include/previous/pybind11/complex.h +61 -0
  112. ctpbee_api/ctp/include/previous/pybind11/detail/class.h +626 -0
  113. ctpbee_api/ctp/include/previous/pybind11/detail/common.h +803 -0
  114. ctpbee_api/ctp/include/previous/pybind11/detail/descr.h +185 -0
  115. ctpbee_api/ctp/include/previous/pybind11/detail/init.h +335 -0
  116. ctpbee_api/ctp/include/previous/pybind11/detail/internals.h +285 -0
  117. ctpbee_api/ctp/include/previous/pybind11/detail/typeid.h +53 -0
  118. ctpbee_api/ctp/include/previous/pybind11/eigen.h +604 -0
  119. ctpbee_api/ctp/include/previous/pybind11/embed.h +194 -0
  120. ctpbee_api/ctp/include/previous/pybind11/eval.h +117 -0
  121. ctpbee_api/ctp/include/previous/pybind11/functional.h +85 -0
  122. ctpbee_api/ctp/include/previous/pybind11/iostream.h +200 -0
  123. ctpbee_api/ctp/include/previous/pybind11/numpy.h +1601 -0
  124. ctpbee_api/ctp/include/previous/pybind11/operators.h +168 -0
  125. ctpbee_api/ctp/include/previous/pybind11/options.h +65 -0
  126. ctpbee_api/ctp/include/previous/pybind11/pybind11.h +1965 -0
  127. ctpbee_api/ctp/include/previous/pybind11/pytypes.h +1332 -0
  128. ctpbee_api/ctp/include/previous/pybind11/stl.h +376 -0
  129. ctpbee_api/ctp/include/previous/pybind11/stl_bind.h +599 -0
  130. ctpbee_api/ctp/libs/libcomunicationkey.a +0 -0
  131. ctpbee_api/ctp/libs/libcrypto.a +0 -0
  132. ctpbee_api/ctp/libs/libssl.a +0 -0
  133. ctpbee_api/ctp/libs/thostmduserapi_se.lib +0 -0
  134. ctpbee_api/ctp/libs/thosttraderapi_se.lib +0 -0
  135. ctpbee_api/ctp/libthostmduserapi_se.so +0 -0
  136. ctpbee_api/ctp/libthosttraderapi_se.so +0 -0
  137. ctpbee_api/ctp/thostmduserapi_se.dll +0 -0
  138. ctpbee_api/ctp/thosttraderapi_se.dll +0 -0
  139. ctpbee_api/ctp/vnctp/vnctp.h +189 -0
  140. ctpbee_api/ctp/vnctp/vnctp.sln +41 -0
  141. ctpbee_api/ctp/vnctp/vnctpmd/dllmain.cpp +19 -0
  142. ctpbee_api/ctp/vnctp/vnctpmd/stdafx.cpp +1 -0
  143. ctpbee_api/ctp/vnctp/vnctpmd/stdafx.h +17 -0
  144. ctpbee_api/ctp/vnctp/vnctpmd/targetver.h +8 -0
  145. ctpbee_api/ctp/vnctp/vnctpmd/vnctpmd.cpp +953 -0
  146. ctpbee_api/ctp/vnctp/vnctpmd/vnctpmd.h +209 -0
  147. ctpbee_api/ctp/vnctp/vnctpmd/vnctpmd.vcxproj +200 -0
  148. ctpbee_api/ctp/vnctp/vnctpmd/vnctpmd.vcxproj.filters +54 -0
  149. ctpbee_api/ctp/vnctp/vnctpmd/vnctpmd.vcxproj.user +4 -0
  150. ctpbee_api/ctp/vnctp/vnctptd/dllmain.cpp +19 -0
  151. ctpbee_api/ctp/vnctp/vnctptd/stdafx.cpp +1 -0
  152. ctpbee_api/ctp/vnctp/vnctptd/stdafx.h +16 -0
  153. ctpbee_api/ctp/vnctp/vnctptd/targetver.h +8 -0
  154. ctpbee_api/ctp/vnctp/vnctptd/vnctptd.cpp +12148 -0
  155. ctpbee_api/ctp/vnctp/vnctptd/vnctptd.h +1329 -0
  156. ctpbee_api/ctp/vnctp/vnctptd/vnctptd.vcxproj +198 -0
  157. ctpbee_api/ctp/vnctp/vnctptd/vnctptd.vcxproj.filters +54 -0
  158. ctpbee_api/ctp/vnctp/vnctptd/vnctptd.vcxproj.user +4 -0
  159. ctpbee_api/ctp/vnctpmd.cp310-win_amd64.pyd +0 -0
  160. ctpbee_api/ctp/vnctptd.cp310-win_amd64.pyd +0 -0
  161. ctpbee_api/ctp_mini/__init__.py +3 -0
  162. ctpbee_api/ctp_mini/generator/generate_api_functions.py +343 -0
  163. ctpbee_api/ctp_mini/generator/generate_data_type.py +76 -0
  164. ctpbee_api/ctp_mini/generator/generate_struct.py +85 -0
  165. ctpbee_api/ctp_mini/generator/mini_constant.py +1186 -0
  166. ctpbee_api/ctp_mini/generator/mini_md_header_define.h +13 -0
  167. ctpbee_api/ctp_mini/generator/mini_md_header_function.h +4 -0
  168. ctpbee_api/ctp_mini/generator/mini_md_header_on.h +26 -0
  169. ctpbee_api/ctp_mini/generator/mini_md_header_process.h +26 -0
  170. ctpbee_api/ctp_mini/generator/mini_md_source_function.cpp +29 -0
  171. ctpbee_api/ctp_mini/generator/mini_md_source_module.cpp +17 -0
  172. ctpbee_api/ctp_mini/generator/mini_md_source_on.cpp +156 -0
  173. ctpbee_api/ctp_mini/generator/mini_md_source_process.cpp +264 -0
  174. ctpbee_api/ctp_mini/generator/mini_md_source_switch.cpp +78 -0
  175. ctpbee_api/ctp_mini/generator/mini_md_source_task.cpp +203 -0
  176. ctpbee_api/ctp_mini/generator/mini_struct.py +4599 -0
  177. ctpbee_api/ctp_mini/generator/mini_td_header_define.h +63 -0
  178. ctpbee_api/ctp_mini/generator/mini_td_header_function.h +84 -0
  179. ctpbee_api/ctp_mini/generator/mini_td_header_on.h +126 -0
  180. ctpbee_api/ctp_mini/generator/mini_td_header_process.h +126 -0
  181. ctpbee_api/ctp_mini/generator/mini_td_source_function.cpp +663 -0
  182. ctpbee_api/ctp_mini/generator/mini_td_source_module.cpp +107 -0
  183. ctpbee_api/ctp_mini/generator/mini_td_source_on.cpp +756 -0
  184. ctpbee_api/ctp_mini/generator/mini_td_source_process.cpp +2492 -0
  185. ctpbee_api/ctp_mini/generator/mini_td_source_switch.cpp +378 -0
  186. ctpbee_api/ctp_mini/generator/mini_td_source_task.cpp +1193 -0
  187. ctpbee_api/ctp_mini/generator/mini_typedef.py +755 -0
  188. ctpbee_api/ctp_mini/generator/package/vnminimd.cpp +886 -0
  189. ctpbee_api/ctp_mini/generator/package/vnminimd.h +205 -0
  190. ctpbee_api/ctp_mini/include/new/mini/ThostFtdcMdApi.h +148 -0
  191. ctpbee_api/ctp_mini/include/new/mini/ThostFtdcTraderApi.h +419 -0
  192. ctpbee_api/ctp_mini/include/new/mini/ThostFtdcUserApiDataType.h +6458 -0
  193. ctpbee_api/ctp_mini/include/new/mini/ThostFtdcUserApiStruct.h +8890 -0
  194. ctpbee_api/ctp_mini/include/new/pybind11/attr.h +690 -0
  195. ctpbee_api/ctp_mini/include/new/pybind11/buffer_info.h +208 -0
  196. ctpbee_api/ctp_mini/include/new/pybind11/cast.h +1704 -0
  197. ctpbee_api/ctp_mini/include/new/pybind11/chrono.h +225 -0
  198. ctpbee_api/ctp_mini/include/new/pybind11/common.h +2 -0
  199. ctpbee_api/ctp_mini/include/new/pybind11/complex.h +74 -0
  200. ctpbee_api/ctp_mini/include/new/pybind11/detail/class.h +743 -0
  201. ctpbee_api/ctp_mini/include/new/pybind11/detail/common.h +1255 -0
  202. ctpbee_api/ctp_mini/include/new/pybind11/detail/descr.h +171 -0
  203. ctpbee_api/ctp_mini/include/new/pybind11/detail/init.h +434 -0
  204. ctpbee_api/ctp_mini/include/new/pybind11/detail/internals.h +656 -0
  205. ctpbee_api/ctp_mini/include/new/pybind11/detail/type_caster_base.h +1177 -0
  206. ctpbee_api/ctp_mini/include/new/pybind11/detail/typeid.h +65 -0
  207. ctpbee_api/ctp_mini/include/new/pybind11/eigen/common.h +9 -0
  208. ctpbee_api/ctp_mini/include/new/pybind11/eigen/matrix.h +714 -0
  209. ctpbee_api/ctp_mini/include/new/pybind11/eigen/tensor.h +516 -0
  210. ctpbee_api/ctp_mini/include/new/pybind11/eigen.h +12 -0
  211. ctpbee_api/ctp_mini/include/new/pybind11/embed.h +316 -0
  212. ctpbee_api/ctp_mini/include/new/pybind11/eval.h +156 -0
  213. ctpbee_api/ctp_mini/include/new/pybind11/functional.h +137 -0
  214. ctpbee_api/ctp_mini/include/new/pybind11/gil.h +239 -0
  215. ctpbee_api/ctp_mini/include/new/pybind11/iostream.h +265 -0
  216. ctpbee_api/ctp_mini/include/new/pybind11/numpy.h +1998 -0
  217. ctpbee_api/ctp_mini/include/new/pybind11/operators.h +202 -0
  218. ctpbee_api/ctp_mini/include/new/pybind11/options.h +92 -0
  219. ctpbee_api/ctp_mini/include/new/pybind11/pybind11.h +2890 -0
  220. ctpbee_api/ctp_mini/include/new/pybind11/pytypes.h +2557 -0
  221. ctpbee_api/ctp_mini/include/new/pybind11/stl/filesystem.h +116 -0
  222. ctpbee_api/ctp_mini/include/new/pybind11/stl.h +447 -0
  223. ctpbee_api/ctp_mini/include/new/pybind11/stl_bind.h +851 -0
  224. ctpbee_api/ctp_mini/include/new/pybind11/type_caster_pyobject_ptr.h +61 -0
  225. ctpbee_api/ctp_mini/include/previous/mini/ThostFtdcMdApi.h +148 -0
  226. ctpbee_api/ctp_mini/include/previous/mini/ThostFtdcTraderApi.h +419 -0
  227. ctpbee_api/ctp_mini/include/previous/mini/ThostFtdcUserApiDataType.h +6458 -0
  228. ctpbee_api/ctp_mini/include/previous/mini/ThostFtdcUserApiStruct.h +8890 -0
  229. ctpbee_api/ctp_mini/include/previous/pybind11/attr.h +489 -0
  230. ctpbee_api/ctp_mini/include/previous/pybind11/buffer_info.h +108 -0
  231. ctpbee_api/ctp_mini/include/previous/pybind11/cast.h +2067 -0
  232. ctpbee_api/ctp_mini/include/previous/pybind11/chrono.h +162 -0
  233. ctpbee_api/ctp_mini/include/previous/pybind11/common.h +2 -0
  234. ctpbee_api/ctp_mini/include/previous/pybind11/complex.h +61 -0
  235. ctpbee_api/ctp_mini/include/previous/pybind11/detail/class.h +626 -0
  236. ctpbee_api/ctp_mini/include/previous/pybind11/detail/common.h +803 -0
  237. ctpbee_api/ctp_mini/include/previous/pybind11/detail/descr.h +185 -0
  238. ctpbee_api/ctp_mini/include/previous/pybind11/detail/init.h +335 -0
  239. ctpbee_api/ctp_mini/include/previous/pybind11/detail/internals.h +285 -0
  240. ctpbee_api/ctp_mini/include/previous/pybind11/detail/typeid.h +53 -0
  241. ctpbee_api/ctp_mini/include/previous/pybind11/eigen.h +604 -0
  242. ctpbee_api/ctp_mini/include/previous/pybind11/embed.h +194 -0
  243. ctpbee_api/ctp_mini/include/previous/pybind11/eval.h +117 -0
  244. ctpbee_api/ctp_mini/include/previous/pybind11/functional.h +85 -0
  245. ctpbee_api/ctp_mini/include/previous/pybind11/iostream.h +200 -0
  246. ctpbee_api/ctp_mini/include/previous/pybind11/numpy.h +1601 -0
  247. ctpbee_api/ctp_mini/include/previous/pybind11/operators.h +168 -0
  248. ctpbee_api/ctp_mini/include/previous/pybind11/options.h +65 -0
  249. ctpbee_api/ctp_mini/include/previous/pybind11/pybind11.h +1965 -0
  250. ctpbee_api/ctp_mini/include/previous/pybind11/pytypes.h +1332 -0
  251. ctpbee_api/ctp_mini/include/previous/pybind11/stl.h +376 -0
  252. ctpbee_api/ctp_mini/include/previous/pybind11/stl_bind.h +599 -0
  253. ctpbee_api/ctp_mini/libs/thostmduserapi.lib +0 -0
  254. ctpbee_api/ctp_mini/libs/thosttraderapi.lib +0 -0
  255. ctpbee_api/ctp_mini/libthostmduserapi.so +0 -0
  256. ctpbee_api/ctp_mini/libthosttraderapi.so +0 -0
  257. ctpbee_api/ctp_mini/mini_constant.py +1186 -0
  258. ctpbee_api/ctp_mini/thostmduserapi.dll +0 -0
  259. ctpbee_api/ctp_mini/thosttraderapi.dll +0 -0
  260. ctpbee_api/ctp_mini/vnctp_mini/vnctp_mini.h +146 -0
  261. ctpbee_api/ctp_mini/vnctp_mini/vnctp_mini.sln +41 -0
  262. ctpbee_api/ctp_mini/vnctp_mini/vnctp_minimd/dllmain.cpp +0 -0
  263. ctpbee_api/ctp_mini/vnctp_mini/vnctp_minimd/stdafx.cpp +0 -0
  264. ctpbee_api/ctp_mini/vnctp_mini/vnctp_minimd/stdafx.h +0 -0
  265. ctpbee_api/ctp_mini/vnctp_mini/vnctp_minimd/targetver.h +0 -0
  266. ctpbee_api/ctp_mini/vnctp_mini/vnctp_minimd/vnctp_minimd.cpp +886 -0
  267. ctpbee_api/ctp_mini/vnctp_mini/vnctp_minimd/vnctp_minimd.h +203 -0
  268. ctpbee_api/ctp_mini/vnctp_mini/vnctp_minimd/vnctp_minimd.vcxproj +183 -0
  269. ctpbee_api/ctp_mini/vnctp_mini/vnctp_minimd/vnctp_minimd.vcxproj.filters +54 -0
  270. ctpbee_api/ctp_mini/vnctp_mini/vnctp_minimd/vnctp_minimd.vcxproj.user +4 -0
  271. ctpbee_api/ctp_mini/vnctp_mini/vnctp_minitd/dllmain.cpp +0 -0
  272. ctpbee_api/ctp_mini/vnctp_mini/vnctp_minitd/stdafx.cpp +0 -0
  273. ctpbee_api/ctp_mini/vnctp_mini/vnctp_minitd/stdafx.h +0 -0
  274. ctpbee_api/ctp_mini/vnctp_mini/vnctp_minitd/targetver.h +0 -0
  275. ctpbee_api/ctp_mini/vnctp_mini/vnctp_minitd/vnctp_minitd.cpp +5716 -0
  276. ctpbee_api/ctp_mini/vnctp_mini/vnctp_minitd/vnctp_minitd.h +680 -0
  277. ctpbee_api/ctp_mini/vnctp_mini/vnctp_minitd/vnctp_minitd.vcxproj +180 -0
  278. ctpbee_api/ctp_mini/vnctp_mini/vnctp_minitd/vnctp_minitd.vcxproj.filters +54 -0
  279. ctpbee_api/ctp_mini/vnctp_mini/vnctp_minitd/vnctp_minitd.vcxproj.user +4 -0
  280. ctpbee_api/ctp_mini/vnctp_minimd.cp310-win_amd64.pyd +0 -0
  281. ctpbee_api/ctp_mini/vnctp_minitd.cp310-win_amd64.pyd +0 -0
  282. ctpbee_api/ctp_mini/vnctp_minitd.lib +0 -0
  283. ctpbee_api/rohon/RohonBaseV64.dll +0 -0
  284. ctpbee_api/rohon/WinDataCollect.dll +0 -0
  285. ctpbee_api/rohon/__init__.py +3 -0
  286. ctpbee_api/rohon/generator/generate_api_functions.py +348 -0
  287. ctpbee_api/rohon/generator/generate_data_type.py +76 -0
  288. ctpbee_api/rohon/generator/generate_struct.py +84 -0
  289. ctpbee_api/rohon/generator/rohon_constant.py +1242 -0
  290. ctpbee_api/rohon/generator/rohon_md_header_define.h +13 -0
  291. ctpbee_api/rohon/generator/rohon_md_header_function.h +6 -0
  292. ctpbee_api/rohon/generator/rohon_md_header_on.h +26 -0
  293. ctpbee_api/rohon/generator/rohon_md_header_process.h +26 -0
  294. ctpbee_api/rohon/generator/rohon_md_source_function.cpp +40 -0
  295. ctpbee_api/rohon/generator/rohon_md_source_module.cpp +18 -0
  296. ctpbee_api/rohon/generator/rohon_md_source_on.cpp +156 -0
  297. ctpbee_api/rohon/generator/rohon_md_source_process.cpp +271 -0
  298. ctpbee_api/rohon/generator/rohon_md_source_switch.cpp +78 -0
  299. ctpbee_api/rohon/generator/rohon_md_source_task.cpp +211 -0
  300. ctpbee_api/rohon/generator/rohon_struct.py +4958 -0
  301. ctpbee_api/rohon/generator/rohon_td_header_define.h +125 -0
  302. ctpbee_api/rohon/generator/rohon_td_header_function.h +164 -0
  303. ctpbee_api/rohon/generator/rohon_td_header_on.h +250 -0
  304. ctpbee_api/rohon/generator/rohon_td_header_process.h +250 -0
  305. ctpbee_api/rohon/generator/rohon_td_source_function.cpp +1338 -0
  306. ctpbee_api/rohon/generator/rohon_td_source_module.cpp +209 -0
  307. ctpbee_api/rohon/generator/rohon_td_source_on.cpp +1500 -0
  308. ctpbee_api/rohon/generator/rohon_td_source_process.cpp +5125 -0
  309. ctpbee_api/rohon/generator/rohon_td_source_switch.cpp +750 -0
  310. ctpbee_api/rohon/generator/rohon_td_source_task.cpp +2339 -0
  311. ctpbee_api/rohon/generator/rohon_typedef.py +781 -0
  312. ctpbee_api/rohon/include/new/pybind11/attr.h +690 -0
  313. ctpbee_api/rohon/include/new/pybind11/buffer_info.h +208 -0
  314. ctpbee_api/rohon/include/new/pybind11/cast.h +1704 -0
  315. ctpbee_api/rohon/include/new/pybind11/chrono.h +225 -0
  316. ctpbee_api/rohon/include/new/pybind11/common.h +2 -0
  317. ctpbee_api/rohon/include/new/pybind11/complex.h +74 -0
  318. ctpbee_api/rohon/include/new/pybind11/detail/class.h +743 -0
  319. ctpbee_api/rohon/include/new/pybind11/detail/common.h +1255 -0
  320. ctpbee_api/rohon/include/new/pybind11/detail/descr.h +171 -0
  321. ctpbee_api/rohon/include/new/pybind11/detail/init.h +434 -0
  322. ctpbee_api/rohon/include/new/pybind11/detail/internals.h +656 -0
  323. ctpbee_api/rohon/include/new/pybind11/detail/type_caster_base.h +1177 -0
  324. ctpbee_api/rohon/include/new/pybind11/detail/typeid.h +65 -0
  325. ctpbee_api/rohon/include/new/pybind11/eigen/common.h +9 -0
  326. ctpbee_api/rohon/include/new/pybind11/eigen/matrix.h +714 -0
  327. ctpbee_api/rohon/include/new/pybind11/eigen/tensor.h +516 -0
  328. ctpbee_api/rohon/include/new/pybind11/eigen.h +12 -0
  329. ctpbee_api/rohon/include/new/pybind11/embed.h +316 -0
  330. ctpbee_api/rohon/include/new/pybind11/eval.h +156 -0
  331. ctpbee_api/rohon/include/new/pybind11/functional.h +137 -0
  332. ctpbee_api/rohon/include/new/pybind11/gil.h +239 -0
  333. ctpbee_api/rohon/include/new/pybind11/iostream.h +265 -0
  334. ctpbee_api/rohon/include/new/pybind11/numpy.h +1998 -0
  335. ctpbee_api/rohon/include/new/pybind11/operators.h +202 -0
  336. ctpbee_api/rohon/include/new/pybind11/options.h +92 -0
  337. ctpbee_api/rohon/include/new/pybind11/pybind11.h +2890 -0
  338. ctpbee_api/rohon/include/new/pybind11/pytypes.h +2557 -0
  339. ctpbee_api/rohon/include/new/pybind11/stl/filesystem.h +116 -0
  340. ctpbee_api/rohon/include/new/pybind11/stl.h +447 -0
  341. ctpbee_api/rohon/include/new/pybind11/stl_bind.h +851 -0
  342. ctpbee_api/rohon/include/new/pybind11/type_caster_pyobject_ptr.h +61 -0
  343. ctpbee_api/rohon/include/new/rohon/ThostFtdcMdApi.h +168 -0
  344. ctpbee_api/rohon/include/new/rohon/ThostFtdcTraderApi.h +739 -0
  345. ctpbee_api/rohon/include/new/rohon/ThostFtdcUserApiDataType.h +6708 -0
  346. ctpbee_api/rohon/include/new/rohon/ThostFtdcUserApiStruct.h +9580 -0
  347. ctpbee_api/rohon/include/previous/pybind11/attr.h +489 -0
  348. ctpbee_api/rohon/include/previous/pybind11/buffer_info.h +108 -0
  349. ctpbee_api/rohon/include/previous/pybind11/cast.h +2067 -0
  350. ctpbee_api/rohon/include/previous/pybind11/chrono.h +162 -0
  351. ctpbee_api/rohon/include/previous/pybind11/common.h +2 -0
  352. ctpbee_api/rohon/include/previous/pybind11/complex.h +61 -0
  353. ctpbee_api/rohon/include/previous/pybind11/detail/class.h +626 -0
  354. ctpbee_api/rohon/include/previous/pybind11/detail/common.h +803 -0
  355. ctpbee_api/rohon/include/previous/pybind11/detail/descr.h +185 -0
  356. ctpbee_api/rohon/include/previous/pybind11/detail/init.h +335 -0
  357. ctpbee_api/rohon/include/previous/pybind11/detail/internals.h +285 -0
  358. ctpbee_api/rohon/include/previous/pybind11/detail/typeid.h +53 -0
  359. ctpbee_api/rohon/include/previous/pybind11/eigen.h +604 -0
  360. ctpbee_api/rohon/include/previous/pybind11/embed.h +194 -0
  361. ctpbee_api/rohon/include/previous/pybind11/eval.h +117 -0
  362. ctpbee_api/rohon/include/previous/pybind11/functional.h +85 -0
  363. ctpbee_api/rohon/include/previous/pybind11/iostream.h +200 -0
  364. ctpbee_api/rohon/include/previous/pybind11/numpy.h +1601 -0
  365. ctpbee_api/rohon/include/previous/pybind11/operators.h +168 -0
  366. ctpbee_api/rohon/include/previous/pybind11/options.h +65 -0
  367. ctpbee_api/rohon/include/previous/pybind11/pybind11.h +1965 -0
  368. ctpbee_api/rohon/include/previous/pybind11/pytypes.h +1332 -0
  369. ctpbee_api/rohon/include/previous/pybind11/stl.h +376 -0
  370. ctpbee_api/rohon/include/previous/pybind11/stl_bind.h +599 -0
  371. ctpbee_api/rohon/include/previous/rohon/ThostFtdcMdApi.h +168 -0
  372. ctpbee_api/rohon/include/previous/rohon/ThostFtdcTraderApi.h +739 -0
  373. ctpbee_api/rohon/include/previous/rohon/ThostFtdcUserApiDataType.h +6708 -0
  374. ctpbee_api/rohon/include/previous/rohon/ThostFtdcUserApiStruct.h +9580 -0
  375. ctpbee_api/rohon/libLinuxDataCollect.so +0 -0
  376. ctpbee_api/rohon/librohonbase.so +0 -0
  377. ctpbee_api/rohon/librohonbase.so.1.1 +0 -0
  378. ctpbee_api/rohon/librohonbase.so.1.1.0.1 +0 -0
  379. ctpbee_api/rohon/libs/thostmduserapi_se.lib +0 -0
  380. ctpbee_api/rohon/libs/thosttraderapi_se.lib +0 -0
  381. ctpbee_api/rohon/libthostmduserapi_se.so +0 -0
  382. ctpbee_api/rohon/libthosttraderapi_se.so +0 -0
  383. ctpbee_api/rohon/rohon_constant.py +1242 -0
  384. ctpbee_api/rohon/thostmduserapi_se.dll +0 -0
  385. ctpbee_api/rohon/thosttraderapi_se.dll +0 -0
  386. ctpbee_api/rohon/vnrohon/.vs/vnrohon/v15/.suo +0 -0
  387. ctpbee_api/rohon/vnrohon/.vs/vnrohon/v15/Browse.VC.db +0 -0
  388. ctpbee_api/rohon/vnrohon/.vs/vnrohon/v15/Solution.VC.db +0 -0
  389. ctpbee_api/rohon/vnrohon/vnrohon.h +147 -0
  390. ctpbee_api/rohon/vnrohon/vnrohon.sln +41 -0
  391. ctpbee_api/rohon/vnrohon/vnrohonmd/dllmain.cpp +19 -0
  392. ctpbee_api/rohon/vnrohon/vnrohonmd/framework.h +5 -0
  393. ctpbee_api/rohon/vnrohon/vnrohonmd/pch.cpp +5 -0
  394. ctpbee_api/rohon/vnrohon/vnrohonmd/pch.h +13 -0
  395. ctpbee_api/rohon/vnrohon/vnrohonmd/vnrohonmd.cpp +931 -0
  396. ctpbee_api/rohon/vnrohon/vnrohonmd/vnrohonmd.h +207 -0
  397. ctpbee_api/rohon/vnrohon/vnrohonmd/vnrohonmd.vcxproj +188 -0
  398. ctpbee_api/rohon/vnrohon/vnrohonmd/vnrohonmd.vcxproj.filters +54 -0
  399. ctpbee_api/rohon/vnrohon/vnrohonmd/vnrohonmd.vcxproj.user +4 -0
  400. ctpbee_api/rohon/vnrohon/vnrohontd/dllmain.cpp +19 -0
  401. ctpbee_api/rohon/vnrohon/vnrohontd/framework.h +5 -0
  402. ctpbee_api/rohon/vnrohon/vnrohontd/pch.cpp +5 -0
  403. ctpbee_api/rohon/vnrohon/vnrohontd/pch.h +13 -0
  404. ctpbee_api/rohon/vnrohon/vnrohontd/vnrohontd.cpp +11395 -0
  405. ctpbee_api/rohon/vnrohon/vnrohontd/vnrohontd.h +1259 -0
  406. ctpbee_api/rohon/vnrohon/vnrohontd/vnrohontd.vcxproj +188 -0
  407. ctpbee_api/rohon/vnrohon/vnrohontd/vnrohontd.vcxproj.filters +54 -0
  408. ctpbee_api/rohon/vnrohon/vnrohontd/vnrohontd.vcxproj.user +4 -0
  409. ctpbee_api/rohon/vnrohonmd.cp310-win_amd64.pyd +0 -0
  410. ctpbee_api/rohon/vnrohontd.cp310-win_amd64.pyd +0 -0
  411. ctpbee_opt_api-0.1.0.dist-info/METADATA +46 -0
  412. ctpbee_opt_api-0.1.0.dist-info/RECORD +414 -0
  413. ctpbee_opt_api-0.1.0.dist-info/WHEEL +5 -0
  414. ctpbee_opt_api-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,2890 @@
1
+ /*
2
+ pybind11/pybind11.h: Main header file of the C++11 python
3
+ binding generator library
4
+
5
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
6
+
7
+ All rights reserved. Use of this source code is governed by a
8
+ BSD-style license that can be found in the LICENSE file.
9
+ */
10
+
11
+ #pragma once
12
+
13
+ #include "detail/class.h"
14
+ #include "detail/init.h"
15
+ #include "attr.h"
16
+ #include "gil.h"
17
+ #include "options.h"
18
+
19
+ #include <cstdlib>
20
+ #include <cstring>
21
+ #include <memory>
22
+ #include <new>
23
+ #include <string>
24
+ #include <utility>
25
+ #include <vector>
26
+
27
+ #if defined(__cpp_lib_launder) && !(defined(_MSC_VER) && (_MSC_VER < 1914))
28
+ # define PYBIND11_STD_LAUNDER std::launder
29
+ # define PYBIND11_HAS_STD_LAUNDER 1
30
+ #else
31
+ # define PYBIND11_STD_LAUNDER
32
+ # define PYBIND11_HAS_STD_LAUNDER 0
33
+ #endif
34
+ #if defined(__GNUG__) && !defined(__clang__)
35
+ # include <cxxabi.h>
36
+ #endif
37
+
38
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
39
+
40
+ /* https://stackoverflow.com/questions/46798456/handling-gccs-noexcept-type-warning
41
+ This warning is about ABI compatibility, not code health.
42
+ It is only actually needed in a couple places, but apparently GCC 7 "generates this warning if
43
+ and only if the first template instantiation ... involves noexcept" [stackoverflow], therefore
44
+ it could get triggered from seemingly random places, depending on user code.
45
+ No other GCC version generates this warning.
46
+ */
47
+ #if defined(__GNUC__) && __GNUC__ == 7
48
+ PYBIND11_WARNING_DISABLE_GCC("-Wnoexcept-type")
49
+ #endif
50
+
51
+ PYBIND11_WARNING_DISABLE_MSVC(4127)
52
+
53
+ PYBIND11_NAMESPACE_BEGIN(detail)
54
+
55
+ // Apply all the extensions translators from a list
56
+ // Return true if one of the translators completed without raising an exception
57
+ // itself. Return of false indicates that if there are other translators
58
+ // available, they should be tried.
59
+ inline bool apply_exception_translators(std::forward_list<ExceptionTranslator> &translators) {
60
+ auto last_exception = std::current_exception();
61
+
62
+ for (auto &translator : translators) {
63
+ try {
64
+ translator(last_exception);
65
+ return true;
66
+ } catch (...) {
67
+ last_exception = std::current_exception();
68
+ }
69
+ }
70
+ return false;
71
+ }
72
+
73
+ #if defined(_MSC_VER)
74
+ # define PYBIND11_COMPAT_STRDUP _strdup
75
+ #else
76
+ # define PYBIND11_COMPAT_STRDUP strdup
77
+ #endif
78
+
79
+ PYBIND11_NAMESPACE_END(detail)
80
+
81
+ /// Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object
82
+ class cpp_function : public function {
83
+ public:
84
+ cpp_function() = default;
85
+ // NOLINTNEXTLINE(google-explicit-constructor)
86
+ cpp_function(std::nullptr_t) {}
87
+ cpp_function(std::nullptr_t, const is_setter &) {}
88
+
89
+ /// Construct a cpp_function from a vanilla function pointer
90
+ template <typename Return, typename... Args, typename... Extra>
91
+ // NOLINTNEXTLINE(google-explicit-constructor)
92
+ cpp_function(Return (*f)(Args...), const Extra &...extra) {
93
+ initialize(f, f, extra...);
94
+ }
95
+
96
+ /// Construct a cpp_function from a lambda function (possibly with internal state)
97
+ template <typename Func,
98
+ typename... Extra,
99
+ typename = detail::enable_if_t<detail::is_lambda<Func>::value>>
100
+ // NOLINTNEXTLINE(google-explicit-constructor)
101
+ cpp_function(Func &&f, const Extra &...extra) {
102
+ initialize(
103
+ std::forward<Func>(f), (detail::function_signature_t<Func> *) nullptr, extra...);
104
+ }
105
+
106
+ /// Construct a cpp_function from a class method (non-const, no ref-qualifier)
107
+ template <typename Return, typename Class, typename... Arg, typename... Extra>
108
+ // NOLINTNEXTLINE(google-explicit-constructor)
109
+ cpp_function(Return (Class::*f)(Arg...), const Extra &...extra) {
110
+ initialize(
111
+ [f](Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
112
+ (Return(*)(Class *, Arg...)) nullptr,
113
+ extra...);
114
+ }
115
+
116
+ /// Construct a cpp_function from a class method (non-const, lvalue ref-qualifier)
117
+ /// A copy of the overload for non-const functions without explicit ref-qualifier
118
+ /// but with an added `&`.
119
+ template <typename Return, typename Class, typename... Arg, typename... Extra>
120
+ // NOLINTNEXTLINE(google-explicit-constructor)
121
+ cpp_function(Return (Class::*f)(Arg...) &, const Extra &...extra) {
122
+ initialize(
123
+ [f](Class *c, Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
124
+ (Return(*)(Class *, Arg...)) nullptr,
125
+ extra...);
126
+ }
127
+
128
+ /// Construct a cpp_function from a class method (const, no ref-qualifier)
129
+ template <typename Return, typename Class, typename... Arg, typename... Extra>
130
+ // NOLINTNEXTLINE(google-explicit-constructor)
131
+ cpp_function(Return (Class::*f)(Arg...) const, const Extra &...extra) {
132
+ initialize([f](const Class *c,
133
+ Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
134
+ (Return(*)(const Class *, Arg...)) nullptr,
135
+ extra...);
136
+ }
137
+
138
+ /// Construct a cpp_function from a class method (const, lvalue ref-qualifier)
139
+ /// A copy of the overload for const functions without explicit ref-qualifier
140
+ /// but with an added `&`.
141
+ template <typename Return, typename Class, typename... Arg, typename... Extra>
142
+ // NOLINTNEXTLINE(google-explicit-constructor)
143
+ cpp_function(Return (Class::*f)(Arg...) const &, const Extra &...extra) {
144
+ initialize([f](const Class *c,
145
+ Arg... args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
146
+ (Return(*)(const Class *, Arg...)) nullptr,
147
+ extra...);
148
+ }
149
+
150
+ /// Return the function name
151
+ object name() const { return attr("__name__"); }
152
+
153
+ protected:
154
+ struct InitializingFunctionRecordDeleter {
155
+ // `destruct(function_record, false)`: `initialize_generic` copies strings and
156
+ // takes care of cleaning up in case of exceptions. So pass `false` to `free_strings`.
157
+ void operator()(detail::function_record *rec) { destruct(rec, false); }
158
+ };
159
+ using unique_function_record
160
+ = std::unique_ptr<detail::function_record, InitializingFunctionRecordDeleter>;
161
+
162
+ /// Space optimization: don't inline this frequently instantiated fragment
163
+ PYBIND11_NOINLINE unique_function_record make_function_record() {
164
+ return unique_function_record(new detail::function_record());
165
+ }
166
+
167
+ /// Special internal constructor for functors, lambda functions, etc.
168
+ template <typename Func, typename Return, typename... Args, typename... Extra>
169
+ void initialize(Func &&f, Return (*)(Args...), const Extra &...extra) {
170
+ using namespace detail;
171
+ struct capture {
172
+ remove_reference_t<Func> f;
173
+ };
174
+
175
+ /* Store the function including any extra state it might have (e.g. a lambda capture
176
+ * object) */
177
+ // The unique_ptr makes sure nothing is leaked in case of an exception.
178
+ auto unique_rec = make_function_record();
179
+ auto *rec = unique_rec.get();
180
+
181
+ /* Store the capture object directly in the function record if there is enough space */
182
+ if (sizeof(capture) <= sizeof(rec->data)) {
183
+ /* Without these pragmas, GCC warns that there might not be
184
+ enough space to use the placement new operator. However, the
185
+ 'if' statement above ensures that this is the case. */
186
+ PYBIND11_WARNING_PUSH
187
+
188
+ #if defined(__GNUG__) && __GNUC__ >= 6
189
+ PYBIND11_WARNING_DISABLE_GCC("-Wplacement-new")
190
+ #endif
191
+
192
+ new ((capture *) &rec->data) capture{std::forward<Func>(f)};
193
+
194
+ #if !PYBIND11_HAS_STD_LAUNDER
195
+ PYBIND11_WARNING_DISABLE_GCC("-Wstrict-aliasing")
196
+ #endif
197
+
198
+ // UB without std::launder, but without breaking ABI and/or
199
+ // a significant refactoring it's "impossible" to solve.
200
+ if (!std::is_trivially_destructible<capture>::value) {
201
+ rec->free_data = [](function_record *r) {
202
+ auto data = PYBIND11_STD_LAUNDER((capture *) &r->data);
203
+ (void) data;
204
+ data->~capture();
205
+ };
206
+ }
207
+ PYBIND11_WARNING_POP
208
+ } else {
209
+ rec->data[0] = new capture{std::forward<Func>(f)};
210
+ rec->free_data = [](function_record *r) { delete ((capture *) r->data[0]); };
211
+ }
212
+
213
+ /* Type casters for the function arguments and return value */
214
+ using cast_in = argument_loader<Args...>;
215
+ using cast_out
216
+ = make_caster<conditional_t<std::is_void<Return>::value, void_type, Return>>;
217
+
218
+ static_assert(
219
+ expected_num_args<Extra...>(
220
+ sizeof...(Args), cast_in::args_pos >= 0, cast_in::has_kwargs),
221
+ "The number of argument annotations does not match the number of function arguments");
222
+
223
+ /* Dispatch code which converts function arguments and performs the actual function call */
224
+ rec->impl = [](function_call &call) -> handle {
225
+ cast_in args_converter;
226
+
227
+ /* Try to cast the function arguments into the C++ domain */
228
+ if (!args_converter.load_args(call)) {
229
+ return PYBIND11_TRY_NEXT_OVERLOAD;
230
+ }
231
+
232
+ /* Invoke call policy pre-call hook */
233
+ process_attributes<Extra...>::precall(call);
234
+
235
+ /* Get a pointer to the capture object */
236
+ const auto *data = (sizeof(capture) <= sizeof(call.func.data) ? &call.func.data
237
+ : call.func.data[0]);
238
+ auto *cap = const_cast<capture *>(reinterpret_cast<const capture *>(data));
239
+
240
+ /* Override policy for rvalues -- usually to enforce rvp::move on an rvalue */
241
+ return_value_policy policy
242
+ = return_value_policy_override<Return>::policy(call.func.policy);
243
+
244
+ /* Function scope guard -- defaults to the compile-to-nothing `void_type` */
245
+ using Guard = extract_guard_t<Extra...>;
246
+
247
+ /* Perform the function call */
248
+ handle result;
249
+ if (call.func.is_setter) {
250
+ (void) std::move(args_converter).template call<Return, Guard>(cap->f);
251
+ result = none().release();
252
+ } else {
253
+ result = cast_out::cast(
254
+ std::move(args_converter).template call<Return, Guard>(cap->f),
255
+ policy,
256
+ call.parent);
257
+ }
258
+
259
+ /* Invoke call policy post-call hook */
260
+ process_attributes<Extra...>::postcall(call, result);
261
+
262
+ return result;
263
+ };
264
+
265
+ rec->nargs_pos = cast_in::args_pos >= 0
266
+ ? static_cast<std::uint16_t>(cast_in::args_pos)
267
+ : sizeof...(Args) - cast_in::has_kwargs; // Will get reduced more if
268
+ // we have a kw_only
269
+ rec->has_args = cast_in::args_pos >= 0;
270
+ rec->has_kwargs = cast_in::has_kwargs;
271
+
272
+ /* Process any user-provided function attributes */
273
+ process_attributes<Extra...>::init(extra..., rec);
274
+
275
+ {
276
+ constexpr bool has_kw_only_args = any_of<std::is_same<kw_only, Extra>...>::value,
277
+ has_pos_only_args = any_of<std::is_same<pos_only, Extra>...>::value,
278
+ has_arg_annotations = any_of<is_keyword<Extra>...>::value;
279
+ static_assert(has_arg_annotations || !has_kw_only_args,
280
+ "py::kw_only requires the use of argument annotations");
281
+ static_assert(has_arg_annotations || !has_pos_only_args,
282
+ "py::pos_only requires the use of argument annotations (for docstrings "
283
+ "and aligning the annotations to the argument)");
284
+
285
+ static_assert(constexpr_sum(is_kw_only<Extra>::value...) <= 1,
286
+ "py::kw_only may be specified only once");
287
+ static_assert(constexpr_sum(is_pos_only<Extra>::value...) <= 1,
288
+ "py::pos_only may be specified only once");
289
+ constexpr auto kw_only_pos = constexpr_first<is_kw_only, Extra...>();
290
+ constexpr auto pos_only_pos = constexpr_first<is_pos_only, Extra...>();
291
+ static_assert(!(has_kw_only_args && has_pos_only_args) || pos_only_pos < kw_only_pos,
292
+ "py::pos_only must come before py::kw_only");
293
+ }
294
+
295
+ /* Generate a readable signature describing the function's arguments and return
296
+ value types */
297
+ static constexpr auto signature
298
+ = const_name("(") + cast_in::arg_names + const_name(") -> ") + cast_out::name;
299
+ PYBIND11_DESCR_CONSTEXPR auto types = decltype(signature)::types();
300
+
301
+ /* Register the function with Python from generic (non-templated) code */
302
+ // Pass on the ownership over the `unique_rec` to `initialize_generic`. `rec` stays valid.
303
+ initialize_generic(std::move(unique_rec), signature.text, types.data(), sizeof...(Args));
304
+
305
+ /* Stash some additional information used by an important optimization in 'functional.h' */
306
+ using FunctionType = Return (*)(Args...);
307
+ constexpr bool is_function_ptr
308
+ = std::is_convertible<Func, FunctionType>::value && sizeof(capture) == sizeof(void *);
309
+ if (is_function_ptr) {
310
+ rec->is_stateless = true;
311
+ rec->data[1]
312
+ = const_cast<void *>(reinterpret_cast<const void *>(&typeid(FunctionType)));
313
+ }
314
+ }
315
+
316
+ // Utility class that keeps track of all duplicated strings, and cleans them up in its
317
+ // destructor, unless they are released. Basically a RAII-solution to deal with exceptions
318
+ // along the way.
319
+ class strdup_guard {
320
+ public:
321
+ strdup_guard() = default;
322
+ strdup_guard(const strdup_guard &) = delete;
323
+ strdup_guard &operator=(const strdup_guard &) = delete;
324
+
325
+ ~strdup_guard() {
326
+ for (auto *s : strings) {
327
+ std::free(s);
328
+ }
329
+ }
330
+ char *operator()(const char *s) {
331
+ auto *t = PYBIND11_COMPAT_STRDUP(s);
332
+ strings.push_back(t);
333
+ return t;
334
+ }
335
+ void release() { strings.clear(); }
336
+
337
+ private:
338
+ std::vector<char *> strings;
339
+ };
340
+
341
+ /// Register a function call with Python (generic non-templated code goes here)
342
+ void initialize_generic(unique_function_record &&unique_rec,
343
+ const char *text,
344
+ const std::type_info *const *types,
345
+ size_t args) {
346
+ // Do NOT receive `unique_rec` by value. If this function fails to move out the unique_ptr,
347
+ // we do not want this to destruct the pointer. `initialize` (the caller) still relies on
348
+ // the pointee being alive after this call. Only move out if a `capsule` is going to keep
349
+ // it alive.
350
+ auto *rec = unique_rec.get();
351
+
352
+ // Keep track of strdup'ed strings, and clean them up as long as the function's capsule
353
+ // has not taken ownership yet (when `unique_rec.release()` is called).
354
+ // Note: This cannot easily be fixed by a `unique_ptr` with custom deleter, because the
355
+ // strings are only referenced before strdup'ing. So only *after* the following block could
356
+ // `destruct` safely be called, but even then, `repr` could still throw in the middle of
357
+ // copying all strings.
358
+ strdup_guard guarded_strdup;
359
+
360
+ /* Create copies of all referenced C-style strings */
361
+ rec->name = guarded_strdup(rec->name ? rec->name : "");
362
+ if (rec->doc) {
363
+ rec->doc = guarded_strdup(rec->doc);
364
+ }
365
+ for (auto &a : rec->args) {
366
+ if (a.name) {
367
+ a.name = guarded_strdup(a.name);
368
+ }
369
+ if (a.descr) {
370
+ a.descr = guarded_strdup(a.descr);
371
+ } else if (a.value) {
372
+ a.descr = guarded_strdup(repr(a.value).cast<std::string>().c_str());
373
+ }
374
+ }
375
+
376
+ rec->is_constructor = (std::strcmp(rec->name, "__init__") == 0)
377
+ || (std::strcmp(rec->name, "__setstate__") == 0);
378
+
379
+ #if defined(PYBIND11_DETAILED_ERROR_MESSAGES) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING)
380
+ if (rec->is_constructor && !rec->is_new_style_constructor) {
381
+ const auto class_name
382
+ = detail::get_fully_qualified_tp_name((PyTypeObject *) rec->scope.ptr());
383
+ const auto func_name = std::string(rec->name);
384
+ PyErr_WarnEx(PyExc_FutureWarning,
385
+ ("pybind11-bound class '" + class_name
386
+ + "' is using an old-style "
387
+ "placement-new '"
388
+ + func_name
389
+ + "' which has been deprecated. See "
390
+ "the upgrade guide in pybind11's docs. This message is only visible "
391
+ "when compiled in debug mode.")
392
+ .c_str(),
393
+ 0);
394
+ }
395
+ #endif
396
+
397
+ /* Generate a proper function signature */
398
+ std::string signature;
399
+ size_t type_index = 0, arg_index = 0;
400
+ bool is_starred = false;
401
+ for (const auto *pc = text; *pc != '\0'; ++pc) {
402
+ const auto c = *pc;
403
+
404
+ if (c == '{') {
405
+ // Write arg name for everything except *args and **kwargs.
406
+ is_starred = *(pc + 1) == '*';
407
+ if (is_starred) {
408
+ continue;
409
+ }
410
+ // Separator for keyword-only arguments, placed before the kw
411
+ // arguments start (unless we are already putting an *args)
412
+ if (!rec->has_args && arg_index == rec->nargs_pos) {
413
+ signature += "*, ";
414
+ }
415
+ if (arg_index < rec->args.size() && rec->args[arg_index].name) {
416
+ signature += rec->args[arg_index].name;
417
+ } else if (arg_index == 0 && rec->is_method) {
418
+ signature += "self";
419
+ } else {
420
+ signature += "arg" + std::to_string(arg_index - (rec->is_method ? 1 : 0));
421
+ }
422
+ signature += ": ";
423
+ } else if (c == '}') {
424
+ // Write default value if available.
425
+ if (!is_starred && arg_index < rec->args.size() && rec->args[arg_index].descr) {
426
+ signature += " = ";
427
+ signature += rec->args[arg_index].descr;
428
+ }
429
+ // Separator for positional-only arguments (placed after the
430
+ // argument, rather than before like *
431
+ if (rec->nargs_pos_only > 0 && (arg_index + 1) == rec->nargs_pos_only) {
432
+ signature += ", /";
433
+ }
434
+ if (!is_starred) {
435
+ arg_index++;
436
+ }
437
+ } else if (c == '%') {
438
+ const std::type_info *t = types[type_index++];
439
+ if (!t) {
440
+ pybind11_fail("Internal error while parsing type signature (1)");
441
+ }
442
+ if (auto *tinfo = detail::get_type_info(*t)) {
443
+ handle th((PyObject *) tinfo->type);
444
+ signature += th.attr("__module__").cast<std::string>() + "."
445
+ + th.attr("__qualname__").cast<std::string>();
446
+ } else if (rec->is_new_style_constructor && arg_index == 0) {
447
+ // A new-style `__init__` takes `self` as `value_and_holder`.
448
+ // Rewrite it to the proper class type.
449
+ signature += rec->scope.attr("__module__").cast<std::string>() + "."
450
+ + rec->scope.attr("__qualname__").cast<std::string>();
451
+ } else {
452
+ std::string tname(t->name());
453
+ detail::clean_type_id(tname);
454
+ signature += tname;
455
+ }
456
+ } else {
457
+ signature += c;
458
+ }
459
+ }
460
+
461
+ if (arg_index != args - rec->has_args - rec->has_kwargs || types[type_index] != nullptr) {
462
+ pybind11_fail("Internal error while parsing type signature (2)");
463
+ }
464
+
465
+ rec->signature = guarded_strdup(signature.c_str());
466
+ rec->args.shrink_to_fit();
467
+ rec->nargs = (std::uint16_t) args;
468
+
469
+ if (rec->sibling && PYBIND11_INSTANCE_METHOD_CHECK(rec->sibling.ptr())) {
470
+ rec->sibling = PYBIND11_INSTANCE_METHOD_GET_FUNCTION(rec->sibling.ptr());
471
+ }
472
+
473
+ detail::function_record *chain = nullptr, *chain_start = rec;
474
+ if (rec->sibling) {
475
+ if (PyCFunction_Check(rec->sibling.ptr())) {
476
+ auto *self = PyCFunction_GET_SELF(rec->sibling.ptr());
477
+ if (!isinstance<capsule>(self)) {
478
+ chain = nullptr;
479
+ } else {
480
+ auto rec_capsule = reinterpret_borrow<capsule>(self);
481
+ if (detail::is_function_record_capsule(rec_capsule)) {
482
+ chain = rec_capsule.get_pointer<detail::function_record>();
483
+ /* Never append a method to an overload chain of a parent class;
484
+ instead, hide the parent's overloads in this case */
485
+ if (!chain->scope.is(rec->scope)) {
486
+ chain = nullptr;
487
+ }
488
+ } else {
489
+ chain = nullptr;
490
+ }
491
+ }
492
+ }
493
+ // Don't trigger for things like the default __init__, which are wrapper_descriptors
494
+ // that we are intentionally replacing
495
+ else if (!rec->sibling.is_none() && rec->name[0] != '_') {
496
+ pybind11_fail("Cannot overload existing non-function object \""
497
+ + std::string(rec->name) + "\" with a function of the same name");
498
+ }
499
+ }
500
+
501
+ if (!chain) {
502
+ /* No existing overload was found, create a new function object */
503
+ rec->def = new PyMethodDef();
504
+ std::memset(rec->def, 0, sizeof(PyMethodDef));
505
+ rec->def->ml_name = rec->name;
506
+ rec->def->ml_meth
507
+ = reinterpret_cast<PyCFunction>(reinterpret_cast<void (*)()>(dispatcher));
508
+ rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
509
+
510
+ capsule rec_capsule(unique_rec.release(),
511
+ detail::get_function_record_capsule_name(),
512
+ [](void *ptr) { destruct((detail::function_record *) ptr); });
513
+ guarded_strdup.release();
514
+
515
+ object scope_module;
516
+ if (rec->scope) {
517
+ if (hasattr(rec->scope, "__module__")) {
518
+ scope_module = rec->scope.attr("__module__");
519
+ } else if (hasattr(rec->scope, "__name__")) {
520
+ scope_module = rec->scope.attr("__name__");
521
+ }
522
+ }
523
+
524
+ m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.ptr(), scope_module.ptr());
525
+ if (!m_ptr) {
526
+ pybind11_fail("cpp_function::cpp_function(): Could not allocate function object");
527
+ }
528
+ } else {
529
+ /* Append at the beginning or end of the overload chain */
530
+ m_ptr = rec->sibling.ptr();
531
+ inc_ref();
532
+ if (chain->is_method != rec->is_method) {
533
+ pybind11_fail(
534
+ "overloading a method with both static and instance methods is not supported; "
535
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
536
+ "#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for more "
537
+ "details"
538
+ #else
539
+ "error while attempting to bind "
540
+ + std::string(rec->is_method ? "instance" : "static") + " method "
541
+ + std::string(pybind11::str(rec->scope.attr("__name__"))) + "."
542
+ + std::string(rec->name) + signature
543
+ #endif
544
+ );
545
+ }
546
+
547
+ if (rec->prepend) {
548
+ // Beginning of chain; we need to replace the capsule's current head-of-the-chain
549
+ // pointer with this one, then make this one point to the previous head of the
550
+ // chain.
551
+ chain_start = rec;
552
+ rec->next = chain;
553
+ auto rec_capsule
554
+ = reinterpret_borrow<capsule>(((PyCFunctionObject *) m_ptr)->m_self);
555
+ rec_capsule.set_pointer(unique_rec.release());
556
+ guarded_strdup.release();
557
+ } else {
558
+ // Or end of chain (normal behavior)
559
+ chain_start = chain;
560
+ while (chain->next) {
561
+ chain = chain->next;
562
+ }
563
+ chain->next = unique_rec.release();
564
+ guarded_strdup.release();
565
+ }
566
+ }
567
+
568
+ std::string signatures;
569
+ int index = 0;
570
+ /* Create a nice pydoc rec including all signatures and
571
+ docstrings of the functions in the overload chain */
572
+ if (chain && options::show_function_signatures()) {
573
+ // First a generic signature
574
+ signatures += rec->name;
575
+ signatures += "(*args, **kwargs)\n";
576
+ signatures += "Overloaded function.\n\n";
577
+ }
578
+ // Then specific overload signatures
579
+ bool first_user_def = true;
580
+ for (auto *it = chain_start; it != nullptr; it = it->next) {
581
+ if (options::show_function_signatures()) {
582
+ if (index > 0) {
583
+ signatures += '\n';
584
+ }
585
+ if (chain) {
586
+ signatures += std::to_string(++index) + ". ";
587
+ }
588
+ signatures += rec->name;
589
+ signatures += it->signature;
590
+ signatures += '\n';
591
+ }
592
+ if (it->doc && it->doc[0] != '\0' && options::show_user_defined_docstrings()) {
593
+ // If we're appending another docstring, and aren't printing function signatures,
594
+ // we need to append a newline first:
595
+ if (!options::show_function_signatures()) {
596
+ if (first_user_def) {
597
+ first_user_def = false;
598
+ } else {
599
+ signatures += '\n';
600
+ }
601
+ }
602
+ if (options::show_function_signatures()) {
603
+ signatures += '\n';
604
+ }
605
+ signatures += it->doc;
606
+ if (options::show_function_signatures()) {
607
+ signatures += '\n';
608
+ }
609
+ }
610
+ }
611
+
612
+ /* Install docstring */
613
+ auto *func = (PyCFunctionObject *) m_ptr;
614
+ std::free(const_cast<char *>(func->m_ml->ml_doc));
615
+ // Install docstring if it's non-empty (when at least one option is enabled)
616
+ func->m_ml->ml_doc
617
+ = signatures.empty() ? nullptr : PYBIND11_COMPAT_STRDUP(signatures.c_str());
618
+
619
+ if (rec->is_method) {
620
+ m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr());
621
+ if (!m_ptr) {
622
+ pybind11_fail(
623
+ "cpp_function::cpp_function(): Could not allocate instance method object");
624
+ }
625
+ Py_DECREF(func);
626
+ }
627
+ }
628
+
629
+ /// When a cpp_function is GCed, release any memory allocated by pybind11
630
+ static void destruct(detail::function_record *rec, bool free_strings = true) {
631
+ // If on Python 3.9, check the interpreter "MICRO" (patch) version.
632
+ // If this is running on 3.9.0, we have to work around a bug.
633
+ #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
634
+ static bool is_zero = Py_GetVersion()[4] == '0';
635
+ #endif
636
+
637
+ while (rec) {
638
+ detail::function_record *next = rec->next;
639
+ if (rec->free_data) {
640
+ rec->free_data(rec);
641
+ }
642
+ // During initialization, these strings might not have been copied yet,
643
+ // so they cannot be freed. Once the function has been created, they can.
644
+ // Check `make_function_record` for more details.
645
+ if (free_strings) {
646
+ std::free((char *) rec->name);
647
+ std::free((char *) rec->doc);
648
+ std::free((char *) rec->signature);
649
+ for (auto &arg : rec->args) {
650
+ std::free(const_cast<char *>(arg.name));
651
+ std::free(const_cast<char *>(arg.descr));
652
+ }
653
+ }
654
+ for (auto &arg : rec->args) {
655
+ arg.value.dec_ref();
656
+ }
657
+ if (rec->def) {
658
+ std::free(const_cast<char *>(rec->def->ml_doc));
659
+ // Python 3.9.0 decref's these in the wrong order; rec->def
660
+ // If loaded on 3.9.0, let these leak (use Python 3.9.1 at runtime to fix)
661
+ // See https://github.com/python/cpython/pull/22670
662
+ #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
663
+ if (!is_zero) {
664
+ delete rec->def;
665
+ }
666
+ #else
667
+ delete rec->def;
668
+ #endif
669
+ }
670
+ delete rec;
671
+ rec = next;
672
+ }
673
+ }
674
+
675
+ /// Main dispatch logic for calls to functions bound using pybind11
676
+ static PyObject *dispatcher(PyObject *self, PyObject *args_in, PyObject *kwargs_in) {
677
+ using namespace detail;
678
+ assert(isinstance<capsule>(self));
679
+
680
+ /* Iterator over the list of potentially admissible overloads */
681
+ const function_record *overloads = reinterpret_cast<function_record *>(
682
+ PyCapsule_GetPointer(self, get_function_record_capsule_name())),
683
+ *it = overloads;
684
+ assert(overloads != nullptr);
685
+
686
+ /* Need to know how many arguments + keyword arguments there are to pick the right
687
+ overload */
688
+ const auto n_args_in = (size_t) PyTuple_GET_SIZE(args_in);
689
+
690
+ handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) : nullptr,
691
+ result = PYBIND11_TRY_NEXT_OVERLOAD;
692
+
693
+ auto self_value_and_holder = value_and_holder();
694
+ if (overloads->is_constructor) {
695
+ if (!parent
696
+ || !PyObject_TypeCheck(parent.ptr(), (PyTypeObject *) overloads->scope.ptr())) {
697
+ PyErr_SetString(
698
+ PyExc_TypeError,
699
+ "__init__(self, ...) called with invalid or missing `self` argument");
700
+ return nullptr;
701
+ }
702
+
703
+ auto *const tinfo = get_type_info((PyTypeObject *) overloads->scope.ptr());
704
+ auto *const pi = reinterpret_cast<instance *>(parent.ptr());
705
+ self_value_and_holder = pi->get_value_and_holder(tinfo, true);
706
+
707
+ // If this value is already registered it must mean __init__ is invoked multiple times;
708
+ // we really can't support that in C++, so just ignore the second __init__.
709
+ if (self_value_and_holder.instance_registered()) {
710
+ return none().release().ptr();
711
+ }
712
+ }
713
+
714
+ try {
715
+ // We do this in two passes: in the first pass, we load arguments with `convert=false`;
716
+ // in the second, we allow conversion (except for arguments with an explicit
717
+ // py::arg().noconvert()). This lets us prefer calls without conversion, with
718
+ // conversion as a fallback.
719
+ std::vector<function_call> second_pass;
720
+
721
+ // However, if there are no overloads, we can just skip the no-convert pass entirely
722
+ const bool overloaded = it != nullptr && it->next != nullptr;
723
+
724
+ for (; it != nullptr; it = it->next) {
725
+
726
+ /* For each overload:
727
+ 1. Copy all positional arguments we were given, also checking to make sure that
728
+ named positional arguments weren't *also* specified via kwarg.
729
+ 2. If we weren't given enough, try to make up the omitted ones by checking
730
+ whether they were provided by a kwarg matching the `py::arg("name")` name. If
731
+ so, use it (and remove it from kwargs); if not, see if the function binding
732
+ provided a default that we can use.
733
+ 3. Ensure that either all keyword arguments were "consumed", or that the
734
+ function takes a kwargs argument to accept unconsumed kwargs.
735
+ 4. Any positional arguments still left get put into a tuple (for args), and any
736
+ leftover kwargs get put into a dict.
737
+ 5. Pack everything into a vector; if we have py::args or py::kwargs, they are an
738
+ extra tuple or dict at the end of the positional arguments.
739
+ 6. Call the function call dispatcher (function_record::impl)
740
+
741
+ If one of these fail, move on to the next overload and keep trying until we get
742
+ a result other than PYBIND11_TRY_NEXT_OVERLOAD.
743
+ */
744
+
745
+ const function_record &func = *it;
746
+ size_t num_args = func.nargs; // Number of positional arguments that we need
747
+ if (func.has_args) {
748
+ --num_args; // (but don't count py::args
749
+ }
750
+ if (func.has_kwargs) {
751
+ --num_args; // or py::kwargs)
752
+ }
753
+ size_t pos_args = func.nargs_pos;
754
+
755
+ if (!func.has_args && n_args_in > pos_args) {
756
+ continue; // Too many positional arguments for this overload
757
+ }
758
+
759
+ if (n_args_in < pos_args && func.args.size() < pos_args) {
760
+ continue; // Not enough positional arguments given, and not enough defaults to
761
+ // fill in the blanks
762
+ }
763
+
764
+ function_call call(func, parent);
765
+
766
+ // Protect std::min with parentheses
767
+ size_t args_to_copy = (std::min)(pos_args, n_args_in);
768
+ size_t args_copied = 0;
769
+
770
+ // 0. Inject new-style `self` argument
771
+ if (func.is_new_style_constructor) {
772
+ // The `value` may have been preallocated by an old-style `__init__`
773
+ // if it was a preceding candidate for overload resolution.
774
+ if (self_value_and_holder) {
775
+ self_value_and_holder.type->dealloc(self_value_and_holder);
776
+ }
777
+
778
+ call.init_self = PyTuple_GET_ITEM(args_in, 0);
779
+ call.args.emplace_back(reinterpret_cast<PyObject *>(&self_value_and_holder));
780
+ call.args_convert.push_back(false);
781
+ ++args_copied;
782
+ }
783
+
784
+ // 1. Copy any position arguments given.
785
+ bool bad_arg = false;
786
+ for (; args_copied < args_to_copy; ++args_copied) {
787
+ const argument_record *arg_rec
788
+ = args_copied < func.args.size() ? &func.args[args_copied] : nullptr;
789
+ if (kwargs_in && arg_rec && arg_rec->name
790
+ && dict_getitemstring(kwargs_in, arg_rec->name)) {
791
+ bad_arg = true;
792
+ break;
793
+ }
794
+
795
+ handle arg(PyTuple_GET_ITEM(args_in, args_copied));
796
+ if (arg_rec && !arg_rec->none && arg.is_none()) {
797
+ bad_arg = true;
798
+ break;
799
+ }
800
+ call.args.push_back(arg);
801
+ call.args_convert.push_back(arg_rec ? arg_rec->convert : true);
802
+ }
803
+ if (bad_arg) {
804
+ continue; // Maybe it was meant for another overload (issue #688)
805
+ }
806
+
807
+ // Keep track of how many position args we copied out in case we need to come back
808
+ // to copy the rest into a py::args argument.
809
+ size_t positional_args_copied = args_copied;
810
+
811
+ // We'll need to copy this if we steal some kwargs for defaults
812
+ dict kwargs = reinterpret_borrow<dict>(kwargs_in);
813
+
814
+ // 1.5. Fill in any missing pos_only args from defaults if they exist
815
+ if (args_copied < func.nargs_pos_only) {
816
+ for (; args_copied < func.nargs_pos_only; ++args_copied) {
817
+ const auto &arg_rec = func.args[args_copied];
818
+ handle value;
819
+
820
+ if (arg_rec.value) {
821
+ value = arg_rec.value;
822
+ }
823
+ if (value) {
824
+ call.args.push_back(value);
825
+ call.args_convert.push_back(arg_rec.convert);
826
+ } else {
827
+ break;
828
+ }
829
+ }
830
+
831
+ if (args_copied < func.nargs_pos_only) {
832
+ continue; // Not enough defaults to fill the positional arguments
833
+ }
834
+ }
835
+
836
+ // 2. Check kwargs and, failing that, defaults that may help complete the list
837
+ if (args_copied < num_args) {
838
+ bool copied_kwargs = false;
839
+
840
+ for (; args_copied < num_args; ++args_copied) {
841
+ const auto &arg_rec = func.args[args_copied];
842
+
843
+ handle value;
844
+ if (kwargs_in && arg_rec.name) {
845
+ value = dict_getitemstring(kwargs.ptr(), arg_rec.name);
846
+ }
847
+
848
+ if (value) {
849
+ // Consume a kwargs value
850
+ if (!copied_kwargs) {
851
+ kwargs = reinterpret_steal<dict>(PyDict_Copy(kwargs.ptr()));
852
+ copied_kwargs = true;
853
+ }
854
+ if (PyDict_DelItemString(kwargs.ptr(), arg_rec.name) == -1) {
855
+ throw error_already_set();
856
+ }
857
+ } else if (arg_rec.value) {
858
+ value = arg_rec.value;
859
+ }
860
+
861
+ if (!arg_rec.none && value.is_none()) {
862
+ break;
863
+ }
864
+
865
+ if (value) {
866
+ // If we're at the py::args index then first insert a stub for it to be
867
+ // replaced later
868
+ if (func.has_args && call.args.size() == func.nargs_pos) {
869
+ call.args.push_back(none());
870
+ }
871
+
872
+ call.args.push_back(value);
873
+ call.args_convert.push_back(arg_rec.convert);
874
+ } else {
875
+ break;
876
+ }
877
+ }
878
+
879
+ if (args_copied < num_args) {
880
+ continue; // Not enough arguments, defaults, or kwargs to fill the
881
+ // positional arguments
882
+ }
883
+ }
884
+
885
+ // 3. Check everything was consumed (unless we have a kwargs arg)
886
+ if (kwargs && !kwargs.empty() && !func.has_kwargs) {
887
+ continue; // Unconsumed kwargs, but no py::kwargs argument to accept them
888
+ }
889
+
890
+ // 4a. If we have a py::args argument, create a new tuple with leftovers
891
+ if (func.has_args) {
892
+ tuple extra_args;
893
+ if (args_to_copy == 0) {
894
+ // We didn't copy out any position arguments from the args_in tuple, so we
895
+ // can reuse it directly without copying:
896
+ extra_args = reinterpret_borrow<tuple>(args_in);
897
+ } else if (positional_args_copied >= n_args_in) {
898
+ extra_args = tuple(0);
899
+ } else {
900
+ size_t args_size = n_args_in - positional_args_copied;
901
+ extra_args = tuple(args_size);
902
+ for (size_t i = 0; i < args_size; ++i) {
903
+ extra_args[i] = PyTuple_GET_ITEM(args_in, positional_args_copied + i);
904
+ }
905
+ }
906
+ if (call.args.size() <= func.nargs_pos) {
907
+ call.args.push_back(extra_args);
908
+ } else {
909
+ call.args[func.nargs_pos] = extra_args;
910
+ }
911
+ call.args_convert.push_back(false);
912
+ call.args_ref = std::move(extra_args);
913
+ }
914
+
915
+ // 4b. If we have a py::kwargs, pass on any remaining kwargs
916
+ if (func.has_kwargs) {
917
+ if (!kwargs.ptr()) {
918
+ kwargs = dict(); // If we didn't get one, send an empty one
919
+ }
920
+ call.args.push_back(kwargs);
921
+ call.args_convert.push_back(false);
922
+ call.kwargs_ref = std::move(kwargs);
923
+ }
924
+
925
+ // 5. Put everything in a vector. Not technically step 5, we've been building it
926
+ // in `call.args` all along.
927
+ #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
928
+ if (call.args.size() != func.nargs || call.args_convert.size() != func.nargs) {
929
+ pybind11_fail("Internal error: function call dispatcher inserted wrong number "
930
+ "of arguments!");
931
+ }
932
+ #endif
933
+
934
+ std::vector<bool> second_pass_convert;
935
+ if (overloaded) {
936
+ // We're in the first no-convert pass, so swap out the conversion flags for a
937
+ // set of all-false flags. If the call fails, we'll swap the flags back in for
938
+ // the conversion-allowed call below.
939
+ second_pass_convert.resize(func.nargs, false);
940
+ call.args_convert.swap(second_pass_convert);
941
+ }
942
+
943
+ // 6. Call the function.
944
+ try {
945
+ loader_life_support guard{};
946
+ result = func.impl(call);
947
+ } catch (reference_cast_error &) {
948
+ result = PYBIND11_TRY_NEXT_OVERLOAD;
949
+ }
950
+
951
+ if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) {
952
+ break;
953
+ }
954
+
955
+ if (overloaded) {
956
+ // The (overloaded) call failed; if the call has at least one argument that
957
+ // permits conversion (i.e. it hasn't been explicitly specified `.noconvert()`)
958
+ // then add this call to the list of second pass overloads to try.
959
+ for (size_t i = func.is_method ? 1 : 0; i < pos_args; i++) {
960
+ if (second_pass_convert[i]) {
961
+ // Found one: swap the converting flags back in and store the call for
962
+ // the second pass.
963
+ call.args_convert.swap(second_pass_convert);
964
+ second_pass.push_back(std::move(call));
965
+ break;
966
+ }
967
+ }
968
+ }
969
+ }
970
+
971
+ if (overloaded && !second_pass.empty() && result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
972
+ // The no-conversion pass finished without success, try again with conversion
973
+ // allowed
974
+ for (auto &call : second_pass) {
975
+ try {
976
+ loader_life_support guard{};
977
+ result = call.func.impl(call);
978
+ } catch (reference_cast_error &) {
979
+ result = PYBIND11_TRY_NEXT_OVERLOAD;
980
+ }
981
+
982
+ if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD) {
983
+ // The error reporting logic below expects 'it' to be valid, as it would be
984
+ // if we'd encountered this failure in the first-pass loop.
985
+ if (!result) {
986
+ it = &call.func;
987
+ }
988
+ break;
989
+ }
990
+ }
991
+ }
992
+ } catch (error_already_set &e) {
993
+ e.restore();
994
+ return nullptr;
995
+ #ifdef __GLIBCXX__
996
+ } catch (abi::__forced_unwind &) {
997
+ throw;
998
+ #endif
999
+ } catch (...) {
1000
+ /* When an exception is caught, give each registered exception
1001
+ translator a chance to translate it to a Python exception. First
1002
+ all module-local translators will be tried in reverse order of
1003
+ registration. If none of the module-locale translators handle
1004
+ the exception (or there are no module-locale translators) then
1005
+ the global translators will be tried, also in reverse order of
1006
+ registration.
1007
+
1008
+ A translator may choose to do one of the following:
1009
+
1010
+ - catch the exception and call PyErr_SetString or PyErr_SetObject
1011
+ to set a standard (or custom) Python exception, or
1012
+ - do nothing and let the exception fall through to the next translator, or
1013
+ - delegate translation to the next translator by throwing a new type of exception.
1014
+ */
1015
+
1016
+ auto &local_exception_translators
1017
+ = get_local_internals().registered_exception_translators;
1018
+ if (detail::apply_exception_translators(local_exception_translators)) {
1019
+ return nullptr;
1020
+ }
1021
+ auto &exception_translators = get_internals().registered_exception_translators;
1022
+ if (detail::apply_exception_translators(exception_translators)) {
1023
+ return nullptr;
1024
+ }
1025
+
1026
+ PyErr_SetString(PyExc_SystemError,
1027
+ "Exception escaped from default exception translator!");
1028
+ return nullptr;
1029
+ }
1030
+
1031
+ auto append_note_if_missing_header_is_suspected = [](std::string &msg) {
1032
+ if (msg.find("std::") != std::string::npos) {
1033
+ msg += "\n\n"
1034
+ "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
1035
+ "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
1036
+ "conversions are optional and require extra headers to be included\n"
1037
+ "when compiling your pybind11 module.";
1038
+ }
1039
+ };
1040
+
1041
+ if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
1042
+ if (overloads->is_operator) {
1043
+ return handle(Py_NotImplemented).inc_ref().ptr();
1044
+ }
1045
+
1046
+ std::string msg = std::string(overloads->name) + "(): incompatible "
1047
+ + std::string(overloads->is_constructor ? "constructor" : "function")
1048
+ + " arguments. The following argument types are supported:\n";
1049
+
1050
+ int ctr = 0;
1051
+ for (const function_record *it2 = overloads; it2 != nullptr; it2 = it2->next) {
1052
+ msg += " " + std::to_string(++ctr) + ". ";
1053
+
1054
+ bool wrote_sig = false;
1055
+ if (overloads->is_constructor) {
1056
+ // For a constructor, rewrite `(self: Object, arg0, ...) -> NoneType` as
1057
+ // `Object(arg0, ...)`
1058
+ std::string sig = it2->signature;
1059
+ size_t start = sig.find('(') + 7; // skip "(self: "
1060
+ if (start < sig.size()) {
1061
+ // End at the , for the next argument
1062
+ size_t end = sig.find(", "), next = end + 2;
1063
+ size_t ret = sig.rfind(" -> ");
1064
+ // Or the ), if there is no comma:
1065
+ if (end >= sig.size()) {
1066
+ next = end = sig.find(')');
1067
+ }
1068
+ if (start < end && next < sig.size()) {
1069
+ msg.append(sig, start, end - start);
1070
+ msg += '(';
1071
+ msg.append(sig, next, ret - next);
1072
+ wrote_sig = true;
1073
+ }
1074
+ }
1075
+ }
1076
+ if (!wrote_sig) {
1077
+ msg += it2->signature;
1078
+ }
1079
+
1080
+ msg += '\n';
1081
+ }
1082
+ msg += "\nInvoked with: ";
1083
+ auto args_ = reinterpret_borrow<tuple>(args_in);
1084
+ bool some_args = false;
1085
+ for (size_t ti = overloads->is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
1086
+ if (!some_args) {
1087
+ some_args = true;
1088
+ } else {
1089
+ msg += ", ";
1090
+ }
1091
+ try {
1092
+ msg += pybind11::repr(args_[ti]);
1093
+ } catch (const error_already_set &) {
1094
+ msg += "<repr raised Error>";
1095
+ }
1096
+ }
1097
+ if (kwargs_in) {
1098
+ auto kwargs = reinterpret_borrow<dict>(kwargs_in);
1099
+ if (!kwargs.empty()) {
1100
+ if (some_args) {
1101
+ msg += "; ";
1102
+ }
1103
+ msg += "kwargs: ";
1104
+ bool first = true;
1105
+ for (auto kwarg : kwargs) {
1106
+ if (first) {
1107
+ first = false;
1108
+ } else {
1109
+ msg += ", ";
1110
+ }
1111
+ msg += pybind11::str("{}=").format(kwarg.first);
1112
+ try {
1113
+ msg += pybind11::repr(kwarg.second);
1114
+ } catch (const error_already_set &) {
1115
+ msg += "<repr raised Error>";
1116
+ }
1117
+ }
1118
+ }
1119
+ }
1120
+
1121
+ append_note_if_missing_header_is_suspected(msg);
1122
+ // Attach additional error info to the exception if supported
1123
+ if (PyErr_Occurred()) {
1124
+ // #HelpAppreciated: unit test coverage for this branch.
1125
+ raise_from(PyExc_TypeError, msg.c_str());
1126
+ return nullptr;
1127
+ }
1128
+ PyErr_SetString(PyExc_TypeError, msg.c_str());
1129
+ return nullptr;
1130
+ }
1131
+ if (!result) {
1132
+ std::string msg = "Unable to convert function return value to a "
1133
+ "Python type! The signature was\n\t";
1134
+ msg += it->signature;
1135
+ append_note_if_missing_header_is_suspected(msg);
1136
+ // Attach additional error info to the exception if supported
1137
+ if (PyErr_Occurred()) {
1138
+ raise_from(PyExc_TypeError, msg.c_str());
1139
+ return nullptr;
1140
+ }
1141
+ PyErr_SetString(PyExc_TypeError, msg.c_str());
1142
+ return nullptr;
1143
+ }
1144
+ if (overloads->is_constructor && !self_value_and_holder.holder_constructed()) {
1145
+ auto *pi = reinterpret_cast<instance *>(parent.ptr());
1146
+ self_value_and_holder.type->init_instance(pi, nullptr);
1147
+ }
1148
+ return result.ptr();
1149
+ }
1150
+ };
1151
+
1152
+ /// Wrapper for Python extension modules
1153
+ class module_ : public object {
1154
+ public:
1155
+ PYBIND11_OBJECT_DEFAULT(module_, object, PyModule_Check)
1156
+
1157
+ /// Create a new top-level Python module with the given name and docstring
1158
+ PYBIND11_DEPRECATED("Use PYBIND11_MODULE or module_::create_extension_module instead")
1159
+ explicit module_(const char *name, const char *doc = nullptr) {
1160
+ *this = create_extension_module(name, doc, new PyModuleDef());
1161
+ }
1162
+
1163
+ /** \rst
1164
+ Create Python binding for a new function within the module scope. ``Func``
1165
+ can be a plain C++ function, a function pointer, or a lambda function. For
1166
+ details on the ``Extra&& ... extra`` argument, see section :ref:`extras`.
1167
+ \endrst */
1168
+ template <typename Func, typename... Extra>
1169
+ module_ &def(const char *name_, Func &&f, const Extra &...extra) {
1170
+ cpp_function func(std::forward<Func>(f),
1171
+ name(name_),
1172
+ scope(*this),
1173
+ sibling(getattr(*this, name_, none())),
1174
+ extra...);
1175
+ // NB: allow overwriting here because cpp_function sets up a chain with the intention of
1176
+ // overwriting (and has already checked internally that it isn't overwriting
1177
+ // non-functions).
1178
+ add_object(name_, func, true /* overwrite */);
1179
+ return *this;
1180
+ }
1181
+
1182
+ /** \rst
1183
+ Create and return a new Python submodule with the given name and docstring.
1184
+ This also works recursively, i.e.
1185
+
1186
+ .. code-block:: cpp
1187
+
1188
+ py::module_ m("example", "pybind11 example plugin");
1189
+ py::module_ m2 = m.def_submodule("sub", "A submodule of 'example'");
1190
+ py::module_ m3 = m2.def_submodule("subsub", "A submodule of 'example.sub'");
1191
+ \endrst */
1192
+ module_ def_submodule(const char *name, const char *doc = nullptr) {
1193
+ const char *this_name = PyModule_GetName(m_ptr);
1194
+ if (this_name == nullptr) {
1195
+ throw error_already_set();
1196
+ }
1197
+ std::string full_name = std::string(this_name) + '.' + name;
1198
+ handle submodule = PyImport_AddModule(full_name.c_str());
1199
+ if (!submodule) {
1200
+ throw error_already_set();
1201
+ }
1202
+ auto result = reinterpret_borrow<module_>(submodule);
1203
+ if (doc && options::show_user_defined_docstrings()) {
1204
+ result.attr("__doc__") = pybind11::str(doc);
1205
+ }
1206
+ attr(name) = result;
1207
+ return result;
1208
+ }
1209
+
1210
+ /// Import and return a module or throws `error_already_set`.
1211
+ static module_ import(const char *name) {
1212
+ PyObject *obj = PyImport_ImportModule(name);
1213
+ if (!obj) {
1214
+ throw error_already_set();
1215
+ }
1216
+ return reinterpret_steal<module_>(obj);
1217
+ }
1218
+
1219
+ /// Reload the module or throws `error_already_set`.
1220
+ void reload() {
1221
+ PyObject *obj = PyImport_ReloadModule(ptr());
1222
+ if (!obj) {
1223
+ throw error_already_set();
1224
+ }
1225
+ *this = reinterpret_steal<module_>(obj);
1226
+ }
1227
+
1228
+ /** \rst
1229
+ Adds an object to the module using the given name. Throws if an object with the given name
1230
+ already exists.
1231
+
1232
+ ``overwrite`` should almost always be false: attempting to overwrite objects that pybind11
1233
+ has established will, in most cases, break things.
1234
+ \endrst */
1235
+ PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite = false) {
1236
+ if (!overwrite && hasattr(*this, name)) {
1237
+ pybind11_fail(
1238
+ "Error during initialization: multiple incompatible definitions with name \""
1239
+ + std::string(name) + "\"");
1240
+ }
1241
+
1242
+ PyModule_AddObject(ptr(), name, obj.inc_ref().ptr() /* steals a reference */);
1243
+ }
1244
+
1245
+ using module_def = PyModuleDef; // TODO: Can this be removed (it was needed only for Python 2)?
1246
+
1247
+ /** \rst
1248
+ Create a new top-level module that can be used as the main module of a C extension.
1249
+
1250
+ ``def`` should point to a statically allocated module_def.
1251
+ \endrst */
1252
+ static module_ create_extension_module(const char *name, const char *doc, module_def *def) {
1253
+ // module_def is PyModuleDef
1254
+ // Placement new (not an allocation).
1255
+ def = new (def)
1256
+ PyModuleDef{/* m_base */ PyModuleDef_HEAD_INIT,
1257
+ /* m_name */ name,
1258
+ /* m_doc */ options::show_user_defined_docstrings() ? doc : nullptr,
1259
+ /* m_size */ -1,
1260
+ /* m_methods */ nullptr,
1261
+ /* m_slots */ nullptr,
1262
+ /* m_traverse */ nullptr,
1263
+ /* m_clear */ nullptr,
1264
+ /* m_free */ nullptr};
1265
+ auto *m = PyModule_Create(def);
1266
+ if (m == nullptr) {
1267
+ if (PyErr_Occurred()) {
1268
+ throw error_already_set();
1269
+ }
1270
+ pybind11_fail("Internal error in module_::create_extension_module()");
1271
+ }
1272
+ // TODO: Should be reinterpret_steal for Python 3, but Python also steals it again when
1273
+ // returned from PyInit_...
1274
+ // For Python 2, reinterpret_borrow was correct.
1275
+ return reinterpret_borrow<module_>(m);
1276
+ }
1277
+ };
1278
+
1279
+ // When inside a namespace (or anywhere as long as it's not the first item on a line),
1280
+ // C++20 allows "module" to be used. This is provided for backward compatibility, and for
1281
+ // simplicity, if someone wants to use py::module for example, that is perfectly safe.
1282
+ using module = module_;
1283
+
1284
+ /// \ingroup python_builtins
1285
+ /// Return a dictionary representing the global variables in the current execution frame,
1286
+ /// or ``__main__.__dict__`` if there is no frame (usually when the interpreter is embedded).
1287
+ inline dict globals() {
1288
+ PyObject *p = PyEval_GetGlobals();
1289
+ return reinterpret_borrow<dict>(p ? p : module_::import("__main__").attr("__dict__").ptr());
1290
+ }
1291
+
1292
+ template <typename... Args, typename = detail::enable_if_t<args_are_all_keyword_or_ds<Args...>()>>
1293
+ PYBIND11_DEPRECATED("make_simple_namespace should be replaced with "
1294
+ "py::module_::import(\"types\").attr(\"SimpleNamespace\") ")
1295
+ object make_simple_namespace(Args &&...args_) {
1296
+ return module_::import("types").attr("SimpleNamespace")(std::forward<Args>(args_)...);
1297
+ }
1298
+
1299
+ PYBIND11_NAMESPACE_BEGIN(detail)
1300
+ /// Generic support for creating new Python heap types
1301
+ class generic_type : public object {
1302
+ public:
1303
+ PYBIND11_OBJECT_DEFAULT(generic_type, object, PyType_Check)
1304
+ protected:
1305
+ void initialize(const type_record &rec) {
1306
+ if (rec.scope && hasattr(rec.scope, "__dict__")
1307
+ && rec.scope.attr("__dict__").contains(rec.name)) {
1308
+ pybind11_fail("generic_type: cannot initialize type \"" + std::string(rec.name)
1309
+ + "\": an object with that name is already defined");
1310
+ }
1311
+
1312
+ if ((rec.module_local ? get_local_type_info(*rec.type) : get_global_type_info(*rec.type))
1313
+ != nullptr) {
1314
+ pybind11_fail("generic_type: type \"" + std::string(rec.name)
1315
+ + "\" is already registered!");
1316
+ }
1317
+
1318
+ m_ptr = make_new_python_type(rec);
1319
+
1320
+ /* Register supplemental type information in C++ dict */
1321
+ auto *tinfo = new detail::type_info();
1322
+ tinfo->type = (PyTypeObject *) m_ptr;
1323
+ tinfo->cpptype = rec.type;
1324
+ tinfo->type_size = rec.type_size;
1325
+ tinfo->type_align = rec.type_align;
1326
+ tinfo->operator_new = rec.operator_new;
1327
+ tinfo->holder_size_in_ptrs = size_in_ptrs(rec.holder_size);
1328
+ tinfo->init_instance = rec.init_instance;
1329
+ tinfo->dealloc = rec.dealloc;
1330
+ tinfo->simple_type = true;
1331
+ tinfo->simple_ancestors = true;
1332
+ tinfo->default_holder = rec.default_holder;
1333
+ tinfo->module_local = rec.module_local;
1334
+
1335
+ auto &internals = get_internals();
1336
+ auto tindex = std::type_index(*rec.type);
1337
+ tinfo->direct_conversions = &internals.direct_conversions[tindex];
1338
+ if (rec.module_local) {
1339
+ get_local_internals().registered_types_cpp[tindex] = tinfo;
1340
+ } else {
1341
+ internals.registered_types_cpp[tindex] = tinfo;
1342
+ }
1343
+ internals.registered_types_py[(PyTypeObject *) m_ptr] = {tinfo};
1344
+
1345
+ if (rec.bases.size() > 1 || rec.multiple_inheritance) {
1346
+ mark_parents_nonsimple(tinfo->type);
1347
+ tinfo->simple_ancestors = false;
1348
+ } else if (rec.bases.size() == 1) {
1349
+ auto *parent_tinfo = get_type_info((PyTypeObject *) rec.bases[0].ptr());
1350
+ assert(parent_tinfo != nullptr);
1351
+ bool parent_simple_ancestors = parent_tinfo->simple_ancestors;
1352
+ tinfo->simple_ancestors = parent_simple_ancestors;
1353
+ // The parent can no longer be a simple type if it has MI and has a child
1354
+ parent_tinfo->simple_type = parent_tinfo->simple_type && parent_simple_ancestors;
1355
+ }
1356
+
1357
+ if (rec.module_local) {
1358
+ // Stash the local typeinfo and loader so that external modules can access it.
1359
+ tinfo->module_local_load = &type_caster_generic::local_load;
1360
+ setattr(m_ptr, PYBIND11_MODULE_LOCAL_ID, capsule(tinfo));
1361
+ }
1362
+ }
1363
+
1364
+ /// Helper function which tags all parents of a type using mult. inheritance
1365
+ void mark_parents_nonsimple(PyTypeObject *value) {
1366
+ auto t = reinterpret_borrow<tuple>(value->tp_bases);
1367
+ for (handle h : t) {
1368
+ auto *tinfo2 = get_type_info((PyTypeObject *) h.ptr());
1369
+ if (tinfo2) {
1370
+ tinfo2->simple_type = false;
1371
+ }
1372
+ mark_parents_nonsimple((PyTypeObject *) h.ptr());
1373
+ }
1374
+ }
1375
+
1376
+ void install_buffer_funcs(buffer_info *(*get_buffer)(PyObject *, void *),
1377
+ void *get_buffer_data) {
1378
+ auto *type = (PyHeapTypeObject *) m_ptr;
1379
+ auto *tinfo = detail::get_type_info(&type->ht_type);
1380
+
1381
+ if (!type->ht_type.tp_as_buffer) {
1382
+ pybind11_fail("To be able to register buffer protocol support for the type '"
1383
+ + get_fully_qualified_tp_name(tinfo->type)
1384
+ + "' the associated class<>(..) invocation must "
1385
+ "include the pybind11::buffer_protocol() annotation!");
1386
+ }
1387
+
1388
+ tinfo->get_buffer = get_buffer;
1389
+ tinfo->get_buffer_data = get_buffer_data;
1390
+ }
1391
+
1392
+ // rec_func must be set for either fget or fset.
1393
+ void def_property_static_impl(const char *name,
1394
+ handle fget,
1395
+ handle fset,
1396
+ detail::function_record *rec_func) {
1397
+ const auto is_static = (rec_func != nullptr) && !(rec_func->is_method && rec_func->scope);
1398
+ const auto has_doc = (rec_func != nullptr) && (rec_func->doc != nullptr)
1399
+ && pybind11::options::show_user_defined_docstrings();
1400
+ auto property = handle(
1401
+ (PyObject *) (is_static ? get_internals().static_property_type : &PyProperty_Type));
1402
+ attr(name) = property(fget.ptr() ? fget : none(),
1403
+ fset.ptr() ? fset : none(),
1404
+ /*deleter*/ none(),
1405
+ pybind11::str(has_doc ? rec_func->doc : ""));
1406
+ }
1407
+ };
1408
+
1409
+ /// Set the pointer to operator new if it exists. The cast is needed because it can be overloaded.
1410
+ template <typename T,
1411
+ typename = void_t<decltype(static_cast<void *(*) (size_t)>(T::operator new))>>
1412
+ void set_operator_new(type_record *r) {
1413
+ r->operator_new = &T::operator new;
1414
+ }
1415
+
1416
+ template <typename>
1417
+ void set_operator_new(...) {}
1418
+
1419
+ template <typename T, typename SFINAE = void>
1420
+ struct has_operator_delete : std::false_type {};
1421
+ template <typename T>
1422
+ struct has_operator_delete<T, void_t<decltype(static_cast<void (*)(void *)>(T::operator delete))>>
1423
+ : std::true_type {};
1424
+ template <typename T, typename SFINAE = void>
1425
+ struct has_operator_delete_size : std::false_type {};
1426
+ template <typename T>
1427
+ struct has_operator_delete_size<
1428
+ T,
1429
+ void_t<decltype(static_cast<void (*)(void *, size_t)>(T::operator delete))>> : std::true_type {
1430
+ };
1431
+ /// Call class-specific delete if it exists or global otherwise. Can also be an overload set.
1432
+ template <typename T, enable_if_t<has_operator_delete<T>::value, int> = 0>
1433
+ void call_operator_delete(T *p, size_t, size_t) {
1434
+ T::operator delete(p);
1435
+ }
1436
+ template <typename T,
1437
+ enable_if_t<!has_operator_delete<T>::value && has_operator_delete_size<T>::value, int>
1438
+ = 0>
1439
+ void call_operator_delete(T *p, size_t s, size_t) {
1440
+ T::operator delete(p, s);
1441
+ }
1442
+
1443
+ inline void call_operator_delete(void *p, size_t s, size_t a) {
1444
+ (void) s;
1445
+ (void) a;
1446
+ #if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
1447
+ if (a > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
1448
+ # ifdef __cpp_sized_deallocation
1449
+ ::operator delete(p, s, std::align_val_t(a));
1450
+ # else
1451
+ ::operator delete(p, std::align_val_t(a));
1452
+ # endif
1453
+ return;
1454
+ }
1455
+ #endif
1456
+ #ifdef __cpp_sized_deallocation
1457
+ ::operator delete(p, s);
1458
+ #else
1459
+ ::operator delete(p);
1460
+ #endif
1461
+ }
1462
+
1463
+ inline void add_class_method(object &cls, const char *name_, const cpp_function &cf) {
1464
+ cls.attr(cf.name()) = cf;
1465
+ if (std::strcmp(name_, "__eq__") == 0 && !cls.attr("__dict__").contains("__hash__")) {
1466
+ cls.attr("__hash__") = none();
1467
+ }
1468
+ }
1469
+
1470
+ PYBIND11_NAMESPACE_END(detail)
1471
+
1472
+ /// Given a pointer to a member function, cast it to its `Derived` version.
1473
+ /// Forward everything else unchanged.
1474
+ template <typename /*Derived*/, typename F>
1475
+ auto method_adaptor(F &&f) -> decltype(std::forward<F>(f)) {
1476
+ return std::forward<F>(f);
1477
+ }
1478
+
1479
+ template <typename Derived, typename Return, typename Class, typename... Args>
1480
+ auto method_adaptor(Return (Class::*pmf)(Args...)) -> Return (Derived::*)(Args...) {
1481
+ static_assert(
1482
+ detail::is_accessible_base_of<Class, Derived>::value,
1483
+ "Cannot bind an inaccessible base class method; use a lambda definition instead");
1484
+ return pmf;
1485
+ }
1486
+
1487
+ template <typename Derived, typename Return, typename Class, typename... Args>
1488
+ auto method_adaptor(Return (Class::*pmf)(Args...) const) -> Return (Derived::*)(Args...) const {
1489
+ static_assert(
1490
+ detail::is_accessible_base_of<Class, Derived>::value,
1491
+ "Cannot bind an inaccessible base class method; use a lambda definition instead");
1492
+ return pmf;
1493
+ }
1494
+
1495
+ template <typename type_, typename... options>
1496
+ class class_ : public detail::generic_type {
1497
+ template <typename T>
1498
+ using is_holder = detail::is_holder_type<type_, T>;
1499
+ template <typename T>
1500
+ using is_subtype = detail::is_strict_base_of<type_, T>;
1501
+ template <typename T>
1502
+ using is_base = detail::is_strict_base_of<T, type_>;
1503
+ // struct instead of using here to help MSVC:
1504
+ template <typename T>
1505
+ struct is_valid_class_option : detail::any_of<is_holder<T>, is_subtype<T>, is_base<T>> {};
1506
+
1507
+ public:
1508
+ using type = type_;
1509
+ using type_alias = detail::exactly_one_t<is_subtype, void, options...>;
1510
+ constexpr static bool has_alias = !std::is_void<type_alias>::value;
1511
+ using holder_type = detail::exactly_one_t<is_holder, std::unique_ptr<type>, options...>;
1512
+
1513
+ static_assert(detail::all_of<is_valid_class_option<options>...>::value,
1514
+ "Unknown/invalid class_ template parameters provided");
1515
+
1516
+ static_assert(!has_alias || std::is_polymorphic<type>::value,
1517
+ "Cannot use an alias class with a non-polymorphic type");
1518
+
1519
+ PYBIND11_OBJECT(class_, generic_type, PyType_Check)
1520
+
1521
+ template <typename... Extra>
1522
+ class_(handle scope, const char *name, const Extra &...extra) {
1523
+ using namespace detail;
1524
+
1525
+ // MI can only be specified via class_ template options, not constructor parameters
1526
+ static_assert(
1527
+ none_of<is_pyobject<Extra>...>::value || // no base class arguments, or:
1528
+ (constexpr_sum(is_pyobject<Extra>::value...) == 1 && // Exactly one base
1529
+ constexpr_sum(is_base<options>::value...) == 0 && // no template option bases
1530
+ // no multiple_inheritance attr
1531
+ none_of<std::is_same<multiple_inheritance, Extra>...>::value),
1532
+ "Error: multiple inheritance bases must be specified via class_ template options");
1533
+
1534
+ type_record record;
1535
+ record.scope = scope;
1536
+ record.name = name;
1537
+ record.type = &typeid(type);
1538
+ record.type_size = sizeof(conditional_t<has_alias, type_alias, type>);
1539
+ record.type_align = alignof(conditional_t<has_alias, type_alias, type> &);
1540
+ record.holder_size = sizeof(holder_type);
1541
+ record.init_instance = init_instance;
1542
+ record.dealloc = dealloc;
1543
+ record.default_holder = detail::is_instantiation<std::unique_ptr, holder_type>::value;
1544
+
1545
+ set_operator_new<type>(&record);
1546
+
1547
+ /* Register base classes specified via template arguments to class_, if any */
1548
+ PYBIND11_EXPAND_SIDE_EFFECTS(add_base<options>(record));
1549
+
1550
+ /* Process optional arguments, if any */
1551
+ process_attributes<Extra...>::init(extra..., &record);
1552
+
1553
+ generic_type::initialize(record);
1554
+
1555
+ if (has_alias) {
1556
+ auto &instances = record.module_local ? get_local_internals().registered_types_cpp
1557
+ : get_internals().registered_types_cpp;
1558
+ instances[std::type_index(typeid(type_alias))]
1559
+ = instances[std::type_index(typeid(type))];
1560
+ }
1561
+ }
1562
+
1563
+ template <typename Base, detail::enable_if_t<is_base<Base>::value, int> = 0>
1564
+ static void add_base(detail::type_record &rec) {
1565
+ rec.add_base(typeid(Base), [](void *src) -> void * {
1566
+ return static_cast<Base *>(reinterpret_cast<type *>(src));
1567
+ });
1568
+ }
1569
+
1570
+ template <typename Base, detail::enable_if_t<!is_base<Base>::value, int> = 0>
1571
+ static void add_base(detail::type_record &) {}
1572
+
1573
+ template <typename Func, typename... Extra>
1574
+ class_ &def(const char *name_, Func &&f, const Extra &...extra) {
1575
+ cpp_function cf(method_adaptor<type>(std::forward<Func>(f)),
1576
+ name(name_),
1577
+ is_method(*this),
1578
+ sibling(getattr(*this, name_, none())),
1579
+ extra...);
1580
+ add_class_method(*this, name_, cf);
1581
+ return *this;
1582
+ }
1583
+
1584
+ template <typename Func, typename... Extra>
1585
+ class_ &def_static(const char *name_, Func &&f, const Extra &...extra) {
1586
+ static_assert(!std::is_member_function_pointer<Func>::value,
1587
+ "def_static(...) called with a non-static member function pointer");
1588
+ cpp_function cf(std::forward<Func>(f),
1589
+ name(name_),
1590
+ scope(*this),
1591
+ sibling(getattr(*this, name_, none())),
1592
+ extra...);
1593
+ auto cf_name = cf.name();
1594
+ attr(std::move(cf_name)) = staticmethod(std::move(cf));
1595
+ return *this;
1596
+ }
1597
+
1598
+ template <typename T, typename... Extra, detail::enable_if_t<T::op_enable_if_hook, int> = 0>
1599
+ class_ &def(const T &op, const Extra &...extra) {
1600
+ op.execute(*this, extra...);
1601
+ return *this;
1602
+ }
1603
+
1604
+ template <typename T, typename... Extra, detail::enable_if_t<T::op_enable_if_hook, int> = 0>
1605
+ class_ &def_cast(const T &op, const Extra &...extra) {
1606
+ op.execute_cast(*this, extra...);
1607
+ return *this;
1608
+ }
1609
+
1610
+ template <typename... Args, typename... Extra>
1611
+ class_ &def(const detail::initimpl::constructor<Args...> &init, const Extra &...extra) {
1612
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(init);
1613
+ init.execute(*this, extra...);
1614
+ return *this;
1615
+ }
1616
+
1617
+ template <typename... Args, typename... Extra>
1618
+ class_ &def(const detail::initimpl::alias_constructor<Args...> &init, const Extra &...extra) {
1619
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(init);
1620
+ init.execute(*this, extra...);
1621
+ return *this;
1622
+ }
1623
+
1624
+ template <typename... Args, typename... Extra>
1625
+ class_ &def(detail::initimpl::factory<Args...> &&init, const Extra &...extra) {
1626
+ std::move(init).execute(*this, extra...);
1627
+ return *this;
1628
+ }
1629
+
1630
+ template <typename... Args, typename... Extra>
1631
+ class_ &def(detail::initimpl::pickle_factory<Args...> &&pf, const Extra &...extra) {
1632
+ std::move(pf).execute(*this, extra...);
1633
+ return *this;
1634
+ }
1635
+
1636
+ template <typename Func>
1637
+ class_ &def_buffer(Func &&func) {
1638
+ struct capture {
1639
+ Func func;
1640
+ };
1641
+ auto *ptr = new capture{std::forward<Func>(func)};
1642
+ install_buffer_funcs(
1643
+ [](PyObject *obj, void *ptr) -> buffer_info * {
1644
+ detail::make_caster<type> caster;
1645
+ if (!caster.load(obj, false)) {
1646
+ return nullptr;
1647
+ }
1648
+ return new buffer_info(((capture *) ptr)->func(std::move(caster)));
1649
+ },
1650
+ ptr);
1651
+ weakref(m_ptr, cpp_function([ptr](handle wr) {
1652
+ delete ptr;
1653
+ wr.dec_ref();
1654
+ }))
1655
+ .release();
1656
+ return *this;
1657
+ }
1658
+
1659
+ template <typename Return, typename Class, typename... Args>
1660
+ class_ &def_buffer(Return (Class::*func)(Args...)) {
1661
+ return def_buffer([func](type &obj) { return (obj.*func)(); });
1662
+ }
1663
+
1664
+ template <typename Return, typename Class, typename... Args>
1665
+ class_ &def_buffer(Return (Class::*func)(Args...) const) {
1666
+ return def_buffer([func](const type &obj) { return (obj.*func)(); });
1667
+ }
1668
+
1669
+ template <typename C, typename D, typename... Extra>
1670
+ class_ &def_readwrite(const char *name, D C::*pm, const Extra &...extra) {
1671
+ static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value,
1672
+ "def_readwrite() requires a class member (or base class member)");
1673
+ cpp_function fget([pm](const type &c) -> const D & { return c.*pm; }, is_method(*this)),
1674
+ fset([pm](type &c, const D &value) { c.*pm = value; }, is_method(*this));
1675
+ def_property(name, fget, fset, return_value_policy::reference_internal, extra...);
1676
+ return *this;
1677
+ }
1678
+
1679
+ template <typename C, typename D, typename... Extra>
1680
+ class_ &def_readonly(const char *name, const D C::*pm, const Extra &...extra) {
1681
+ static_assert(std::is_same<C, type>::value || std::is_base_of<C, type>::value,
1682
+ "def_readonly() requires a class member (or base class member)");
1683
+ cpp_function fget([pm](const type &c) -> const D & { return c.*pm; }, is_method(*this));
1684
+ def_property_readonly(name, fget, return_value_policy::reference_internal, extra...);
1685
+ return *this;
1686
+ }
1687
+
1688
+ template <typename D, typename... Extra>
1689
+ class_ &def_readwrite_static(const char *name, D *pm, const Extra &...extra) {
1690
+ cpp_function fget([pm](const object &) -> const D & { return *pm; }, scope(*this)),
1691
+ fset([pm](const object &, const D &value) { *pm = value; }, scope(*this));
1692
+ def_property_static(name, fget, fset, return_value_policy::reference, extra...);
1693
+ return *this;
1694
+ }
1695
+
1696
+ template <typename D, typename... Extra>
1697
+ class_ &def_readonly_static(const char *name, const D *pm, const Extra &...extra) {
1698
+ cpp_function fget([pm](const object &) -> const D & { return *pm; }, scope(*this));
1699
+ def_property_readonly_static(name, fget, return_value_policy::reference, extra...);
1700
+ return *this;
1701
+ }
1702
+
1703
+ /// Uses return_value_policy::reference_internal by default
1704
+ template <typename Getter, typename... Extra>
1705
+ class_ &def_property_readonly(const char *name, const Getter &fget, const Extra &...extra) {
1706
+ return def_property_readonly(name,
1707
+ cpp_function(method_adaptor<type>(fget)),
1708
+ return_value_policy::reference_internal,
1709
+ extra...);
1710
+ }
1711
+
1712
+ /// Uses cpp_function's return_value_policy by default
1713
+ template <typename... Extra>
1714
+ class_ &
1715
+ def_property_readonly(const char *name, const cpp_function &fget, const Extra &...extra) {
1716
+ return def_property(name, fget, nullptr, extra...);
1717
+ }
1718
+
1719
+ /// Uses return_value_policy::reference by default
1720
+ template <typename Getter, typename... Extra>
1721
+ class_ &
1722
+ def_property_readonly_static(const char *name, const Getter &fget, const Extra &...extra) {
1723
+ return def_property_readonly_static(
1724
+ name, cpp_function(fget), return_value_policy::reference, extra...);
1725
+ }
1726
+
1727
+ /// Uses cpp_function's return_value_policy by default
1728
+ template <typename... Extra>
1729
+ class_ &def_property_readonly_static(const char *name,
1730
+ const cpp_function &fget,
1731
+ const Extra &...extra) {
1732
+ return def_property_static(name, fget, nullptr, extra...);
1733
+ }
1734
+
1735
+ /// Uses return_value_policy::reference_internal by default
1736
+ template <typename Getter, typename Setter, typename... Extra>
1737
+ class_ &
1738
+ def_property(const char *name, const Getter &fget, const Setter &fset, const Extra &...extra) {
1739
+ return def_property(
1740
+ name, fget, cpp_function(method_adaptor<type>(fset), is_setter()), extra...);
1741
+ }
1742
+ template <typename Getter, typename... Extra>
1743
+ class_ &def_property(const char *name,
1744
+ const Getter &fget,
1745
+ const cpp_function &fset,
1746
+ const Extra &...extra) {
1747
+ return def_property(name,
1748
+ cpp_function(method_adaptor<type>(fget)),
1749
+ fset,
1750
+ return_value_policy::reference_internal,
1751
+ extra...);
1752
+ }
1753
+
1754
+ /// Uses cpp_function's return_value_policy by default
1755
+ template <typename... Extra>
1756
+ class_ &def_property(const char *name,
1757
+ const cpp_function &fget,
1758
+ const cpp_function &fset,
1759
+ const Extra &...extra) {
1760
+ return def_property_static(name, fget, fset, is_method(*this), extra...);
1761
+ }
1762
+
1763
+ /// Uses return_value_policy::reference by default
1764
+ template <typename Getter, typename... Extra>
1765
+ class_ &def_property_static(const char *name,
1766
+ const Getter &fget,
1767
+ const cpp_function &fset,
1768
+ const Extra &...extra) {
1769
+ return def_property_static(
1770
+ name, cpp_function(fget), fset, return_value_policy::reference, extra...);
1771
+ }
1772
+
1773
+ /// Uses cpp_function's return_value_policy by default
1774
+ template <typename... Extra>
1775
+ class_ &def_property_static(const char *name,
1776
+ const cpp_function &fget,
1777
+ const cpp_function &fset,
1778
+ const Extra &...extra) {
1779
+ static_assert(0 == detail::constexpr_sum(std::is_base_of<arg, Extra>::value...),
1780
+ "Argument annotations are not allowed for properties");
1781
+ auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
1782
+ auto *rec_active = rec_fget;
1783
+ if (rec_fget) {
1784
+ char *doc_prev = rec_fget->doc; /* 'extra' field may include a property-specific
1785
+ documentation string */
1786
+ detail::process_attributes<Extra...>::init(extra..., rec_fget);
1787
+ if (rec_fget->doc && rec_fget->doc != doc_prev) {
1788
+ std::free(doc_prev);
1789
+ rec_fget->doc = PYBIND11_COMPAT_STRDUP(rec_fget->doc);
1790
+ }
1791
+ }
1792
+ if (rec_fset) {
1793
+ char *doc_prev = rec_fset->doc;
1794
+ detail::process_attributes<Extra...>::init(extra..., rec_fset);
1795
+ if (rec_fset->doc && rec_fset->doc != doc_prev) {
1796
+ std::free(doc_prev);
1797
+ rec_fset->doc = PYBIND11_COMPAT_STRDUP(rec_fset->doc);
1798
+ }
1799
+ if (!rec_active) {
1800
+ rec_active = rec_fset;
1801
+ }
1802
+ }
1803
+ def_property_static_impl(name, fget, fset, rec_active);
1804
+ return *this;
1805
+ }
1806
+
1807
+ private:
1808
+ /// Initialize holder object, variant 1: object derives from enable_shared_from_this
1809
+ template <typename T>
1810
+ static void init_holder(detail::instance *inst,
1811
+ detail::value_and_holder &v_h,
1812
+ const holder_type * /* unused */,
1813
+ const std::enable_shared_from_this<T> * /* dummy */) {
1814
+
1815
+ auto sh = std::dynamic_pointer_cast<typename holder_type::element_type>(
1816
+ detail::try_get_shared_from_this(v_h.value_ptr<type>()));
1817
+ if (sh) {
1818
+ new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(sh));
1819
+ v_h.set_holder_constructed();
1820
+ }
1821
+
1822
+ if (!v_h.holder_constructed() && inst->owned) {
1823
+ new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
1824
+ v_h.set_holder_constructed();
1825
+ }
1826
+ }
1827
+
1828
+ static void init_holder_from_existing(const detail::value_and_holder &v_h,
1829
+ const holder_type *holder_ptr,
1830
+ std::true_type /*is_copy_constructible*/) {
1831
+ new (std::addressof(v_h.holder<holder_type>()))
1832
+ holder_type(*reinterpret_cast<const holder_type *>(holder_ptr));
1833
+ }
1834
+
1835
+ static void init_holder_from_existing(const detail::value_and_holder &v_h,
1836
+ const holder_type *holder_ptr,
1837
+ std::false_type /*is_copy_constructible*/) {
1838
+ new (std::addressof(v_h.holder<holder_type>()))
1839
+ holder_type(std::move(*const_cast<holder_type *>(holder_ptr)));
1840
+ }
1841
+
1842
+ /// Initialize holder object, variant 2: try to construct from existing holder object, if
1843
+ /// possible
1844
+ static void init_holder(detail::instance *inst,
1845
+ detail::value_and_holder &v_h,
1846
+ const holder_type *holder_ptr,
1847
+ const void * /* dummy -- not enable_shared_from_this<T>) */) {
1848
+ if (holder_ptr) {
1849
+ init_holder_from_existing(v_h, holder_ptr, std::is_copy_constructible<holder_type>());
1850
+ v_h.set_holder_constructed();
1851
+ } else if (detail::always_construct_holder<holder_type>::value || inst->owned) {
1852
+ new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
1853
+ v_h.set_holder_constructed();
1854
+ }
1855
+ }
1856
+
1857
+ /// Performs instance initialization including constructing a holder and registering the known
1858
+ /// instance. Should be called as soon as the `type` value_ptr is set for an instance. Takes
1859
+ /// an optional pointer to an existing holder to use; if not specified and the instance is
1860
+ /// `.owned`, a new holder will be constructed to manage the value pointer.
1861
+ static void init_instance(detail::instance *inst, const void *holder_ptr) {
1862
+ auto v_h = inst->get_value_and_holder(detail::get_type_info(typeid(type)));
1863
+ if (!v_h.instance_registered()) {
1864
+ register_instance(inst, v_h.value_ptr(), v_h.type);
1865
+ v_h.set_instance_registered();
1866
+ }
1867
+ init_holder(inst, v_h, (const holder_type *) holder_ptr, v_h.value_ptr<type>());
1868
+ }
1869
+
1870
+ /// Deallocates an instance; via holder, if constructed; otherwise via operator delete.
1871
+ static void dealloc(detail::value_and_holder &v_h) {
1872
+ // We could be deallocating because we are cleaning up after a Python exception.
1873
+ // If so, the Python error indicator will be set. We need to clear that before
1874
+ // running the destructor, in case the destructor code calls more Python.
1875
+ // If we don't, the Python API will exit with an exception, and pybind11 will
1876
+ // throw error_already_set from the C++ destructor which is forbidden and triggers
1877
+ // std::terminate().
1878
+ error_scope scope;
1879
+ if (v_h.holder_constructed()) {
1880
+ v_h.holder<holder_type>().~holder_type();
1881
+ v_h.set_holder_constructed(false);
1882
+ } else {
1883
+ detail::call_operator_delete(
1884
+ v_h.value_ptr<type>(), v_h.type->type_size, v_h.type->type_align);
1885
+ }
1886
+ v_h.value_ptr() = nullptr;
1887
+ }
1888
+
1889
+ static detail::function_record *get_function_record(handle h) {
1890
+ h = detail::get_function(h);
1891
+ if (!h) {
1892
+ return nullptr;
1893
+ }
1894
+
1895
+ handle func_self = PyCFunction_GET_SELF(h.ptr());
1896
+ if (!func_self) {
1897
+ throw error_already_set();
1898
+ }
1899
+ if (!isinstance<capsule>(func_self)) {
1900
+ return nullptr;
1901
+ }
1902
+ auto cap = reinterpret_borrow<capsule>(func_self);
1903
+ if (!detail::is_function_record_capsule(cap)) {
1904
+ return nullptr;
1905
+ }
1906
+ return cap.get_pointer<detail::function_record>();
1907
+ }
1908
+ };
1909
+
1910
+ /// Binds an existing constructor taking arguments Args...
1911
+ template <typename... Args>
1912
+ detail::initimpl::constructor<Args...> init() {
1913
+ return {};
1914
+ }
1915
+ /// Like `init<Args...>()`, but the instance is always constructed through the alias class (even
1916
+ /// when not inheriting on the Python side).
1917
+ template <typename... Args>
1918
+ detail::initimpl::alias_constructor<Args...> init_alias() {
1919
+ return {};
1920
+ }
1921
+
1922
+ /// Binds a factory function as a constructor
1923
+ template <typename Func, typename Ret = detail::initimpl::factory<Func>>
1924
+ Ret init(Func &&f) {
1925
+ return {std::forward<Func>(f)};
1926
+ }
1927
+
1928
+ /// Dual-argument factory function: the first function is called when no alias is needed, the
1929
+ /// second when an alias is needed (i.e. due to python-side inheritance). Arguments must be
1930
+ /// identical.
1931
+ template <typename CFunc, typename AFunc, typename Ret = detail::initimpl::factory<CFunc, AFunc>>
1932
+ Ret init(CFunc &&c, AFunc &&a) {
1933
+ return {std::forward<CFunc>(c), std::forward<AFunc>(a)};
1934
+ }
1935
+
1936
+ /// Binds pickling functions `__getstate__` and `__setstate__` and ensures that the type
1937
+ /// returned by `__getstate__` is the same as the argument accepted by `__setstate__`.
1938
+ template <typename GetState, typename SetState>
1939
+ detail::initimpl::pickle_factory<GetState, SetState> pickle(GetState &&g, SetState &&s) {
1940
+ return {std::forward<GetState>(g), std::forward<SetState>(s)};
1941
+ }
1942
+
1943
+ PYBIND11_NAMESPACE_BEGIN(detail)
1944
+
1945
+ inline str enum_name(handle arg) {
1946
+ dict entries = arg.get_type().attr("__entries");
1947
+ for (auto kv : entries) {
1948
+ if (handle(kv.second[int_(0)]).equal(arg)) {
1949
+ return pybind11::str(kv.first);
1950
+ }
1951
+ }
1952
+ return "???";
1953
+ }
1954
+
1955
+ struct enum_base {
1956
+ enum_base(const handle &base, const handle &parent) : m_base(base), m_parent(parent) {}
1957
+
1958
+ PYBIND11_NOINLINE void init(bool is_arithmetic, bool is_convertible) {
1959
+ m_base.attr("__entries") = dict();
1960
+ auto property = handle((PyObject *) &PyProperty_Type);
1961
+ auto static_property = handle((PyObject *) get_internals().static_property_type);
1962
+
1963
+ m_base.attr("__repr__") = cpp_function(
1964
+ [](const object &arg) -> str {
1965
+ handle type = type::handle_of(arg);
1966
+ object type_name = type.attr("__name__");
1967
+ return pybind11::str("<{}.{}: {}>")
1968
+ .format(std::move(type_name), enum_name(arg), int_(arg));
1969
+ },
1970
+ name("__repr__"),
1971
+ is_method(m_base));
1972
+
1973
+ m_base.attr("name") = property(cpp_function(&enum_name, name("name"), is_method(m_base)));
1974
+
1975
+ m_base.attr("__str__") = cpp_function(
1976
+ [](handle arg) -> str {
1977
+ object type_name = type::handle_of(arg).attr("__name__");
1978
+ return pybind11::str("{}.{}").format(std::move(type_name), enum_name(arg));
1979
+ },
1980
+ name("name"),
1981
+ is_method(m_base));
1982
+
1983
+ if (options::show_enum_members_docstring()) {
1984
+ m_base.attr("__doc__") = static_property(
1985
+ cpp_function(
1986
+ [](handle arg) -> std::string {
1987
+ std::string docstring;
1988
+ dict entries = arg.attr("__entries");
1989
+ if (((PyTypeObject *) arg.ptr())->tp_doc) {
1990
+ docstring += std::string(
1991
+ reinterpret_cast<PyTypeObject *>(arg.ptr())->tp_doc);
1992
+ docstring += "\n\n";
1993
+ }
1994
+ docstring += "Members:";
1995
+ for (auto kv : entries) {
1996
+ auto key = std::string(pybind11::str(kv.first));
1997
+ auto comment = kv.second[int_(1)];
1998
+ docstring += "\n\n ";
1999
+ docstring += key;
2000
+ if (!comment.is_none()) {
2001
+ docstring += " : ";
2002
+ docstring += pybind11::str(comment).cast<std::string>();
2003
+ }
2004
+ }
2005
+ return docstring;
2006
+ },
2007
+ name("__doc__")),
2008
+ none(),
2009
+ none(),
2010
+ "");
2011
+ }
2012
+
2013
+ m_base.attr("__members__") = static_property(cpp_function(
2014
+ [](handle arg) -> dict {
2015
+ dict entries = arg.attr("__entries"),
2016
+ m;
2017
+ for (auto kv : entries) {
2018
+ m[kv.first] = kv.second[int_(0)];
2019
+ }
2020
+ return m;
2021
+ },
2022
+ name("__members__")),
2023
+ none(),
2024
+ none(),
2025
+ "");
2026
+
2027
+ #define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior) \
2028
+ m_base.attr(op) = cpp_function( \
2029
+ [](const object &a, const object &b) { \
2030
+ if (!type::handle_of(a).is(type::handle_of(b))) \
2031
+ strict_behavior; /* NOLINT(bugprone-macro-parentheses) */ \
2032
+ return expr; \
2033
+ }, \
2034
+ name(op), \
2035
+ is_method(m_base), \
2036
+ arg("other"))
2037
+
2038
+ #define PYBIND11_ENUM_OP_CONV(op, expr) \
2039
+ m_base.attr(op) = cpp_function( \
2040
+ [](const object &a_, const object &b_) { \
2041
+ int_ a(a_), b(b_); \
2042
+ return expr; \
2043
+ }, \
2044
+ name(op), \
2045
+ is_method(m_base), \
2046
+ arg("other"))
2047
+
2048
+ #define PYBIND11_ENUM_OP_CONV_LHS(op, expr) \
2049
+ m_base.attr(op) = cpp_function( \
2050
+ [](const object &a_, const object &b) { \
2051
+ int_ a(a_); \
2052
+ return expr; \
2053
+ }, \
2054
+ name(op), \
2055
+ is_method(m_base), \
2056
+ arg("other"))
2057
+
2058
+ if (is_convertible) {
2059
+ PYBIND11_ENUM_OP_CONV_LHS("__eq__", !b.is_none() && a.equal(b));
2060
+ PYBIND11_ENUM_OP_CONV_LHS("__ne__", b.is_none() || !a.equal(b));
2061
+
2062
+ if (is_arithmetic) {
2063
+ PYBIND11_ENUM_OP_CONV("__lt__", a < b);
2064
+ PYBIND11_ENUM_OP_CONV("__gt__", a > b);
2065
+ PYBIND11_ENUM_OP_CONV("__le__", a <= b);
2066
+ PYBIND11_ENUM_OP_CONV("__ge__", a >= b);
2067
+ PYBIND11_ENUM_OP_CONV("__and__", a & b);
2068
+ PYBIND11_ENUM_OP_CONV("__rand__", a & b);
2069
+ PYBIND11_ENUM_OP_CONV("__or__", a | b);
2070
+ PYBIND11_ENUM_OP_CONV("__ror__", a | b);
2071
+ PYBIND11_ENUM_OP_CONV("__xor__", a ^ b);
2072
+ PYBIND11_ENUM_OP_CONV("__rxor__", a ^ b);
2073
+ m_base.attr("__invert__")
2074
+ = cpp_function([](const object &arg) { return ~(int_(arg)); },
2075
+ name("__invert__"),
2076
+ is_method(m_base));
2077
+ }
2078
+ } else {
2079
+ PYBIND11_ENUM_OP_STRICT("__eq__", int_(a).equal(int_(b)), return false);
2080
+ PYBIND11_ENUM_OP_STRICT("__ne__", !int_(a).equal(int_(b)), return true);
2081
+
2082
+ if (is_arithmetic) {
2083
+ #define PYBIND11_THROW throw type_error("Expected an enumeration of matching type!");
2084
+ PYBIND11_ENUM_OP_STRICT("__lt__", int_(a) < int_(b), PYBIND11_THROW);
2085
+ PYBIND11_ENUM_OP_STRICT("__gt__", int_(a) > int_(b), PYBIND11_THROW);
2086
+ PYBIND11_ENUM_OP_STRICT("__le__", int_(a) <= int_(b), PYBIND11_THROW);
2087
+ PYBIND11_ENUM_OP_STRICT("__ge__", int_(a) >= int_(b), PYBIND11_THROW);
2088
+ #undef PYBIND11_THROW
2089
+ }
2090
+ }
2091
+
2092
+ #undef PYBIND11_ENUM_OP_CONV_LHS
2093
+ #undef PYBIND11_ENUM_OP_CONV
2094
+ #undef PYBIND11_ENUM_OP_STRICT
2095
+
2096
+ m_base.attr("__getstate__") = cpp_function(
2097
+ [](const object &arg) { return int_(arg); }, name("__getstate__"), is_method(m_base));
2098
+
2099
+ m_base.attr("__hash__") = cpp_function(
2100
+ [](const object &arg) { return int_(arg); }, name("__hash__"), is_method(m_base));
2101
+ }
2102
+
2103
+ PYBIND11_NOINLINE void value(char const *name_, object value, const char *doc = nullptr) {
2104
+ dict entries = m_base.attr("__entries");
2105
+ str name(name_);
2106
+ if (entries.contains(name)) {
2107
+ std::string type_name = (std::string) str(m_base.attr("__name__"));
2108
+ throw value_error(std::move(type_name) + ": element \"" + std::string(name_)
2109
+ + "\" already exists!");
2110
+ }
2111
+
2112
+ entries[name] = pybind11::make_tuple(value, doc);
2113
+ m_base.attr(std::move(name)) = std::move(value);
2114
+ }
2115
+
2116
+ PYBIND11_NOINLINE void export_values() {
2117
+ dict entries = m_base.attr("__entries");
2118
+ for (auto kv : entries) {
2119
+ m_parent.attr(kv.first) = kv.second[int_(0)];
2120
+ }
2121
+ }
2122
+
2123
+ handle m_base;
2124
+ handle m_parent;
2125
+ };
2126
+
2127
+ template <bool is_signed, size_t length>
2128
+ struct equivalent_integer {};
2129
+ template <>
2130
+ struct equivalent_integer<true, 1> {
2131
+ using type = int8_t;
2132
+ };
2133
+ template <>
2134
+ struct equivalent_integer<false, 1> {
2135
+ using type = uint8_t;
2136
+ };
2137
+ template <>
2138
+ struct equivalent_integer<true, 2> {
2139
+ using type = int16_t;
2140
+ };
2141
+ template <>
2142
+ struct equivalent_integer<false, 2> {
2143
+ using type = uint16_t;
2144
+ };
2145
+ template <>
2146
+ struct equivalent_integer<true, 4> {
2147
+ using type = int32_t;
2148
+ };
2149
+ template <>
2150
+ struct equivalent_integer<false, 4> {
2151
+ using type = uint32_t;
2152
+ };
2153
+ template <>
2154
+ struct equivalent_integer<true, 8> {
2155
+ using type = int64_t;
2156
+ };
2157
+ template <>
2158
+ struct equivalent_integer<false, 8> {
2159
+ using type = uint64_t;
2160
+ };
2161
+
2162
+ template <typename IntLike>
2163
+ using equivalent_integer_t =
2164
+ typename equivalent_integer<std::is_signed<IntLike>::value, sizeof(IntLike)>::type;
2165
+
2166
+ PYBIND11_NAMESPACE_END(detail)
2167
+
2168
+ /// Binds C++ enumerations and enumeration classes to Python
2169
+ template <typename Type>
2170
+ class enum_ : public class_<Type> {
2171
+ public:
2172
+ using Base = class_<Type>;
2173
+ using Base::attr;
2174
+ using Base::def;
2175
+ using Base::def_property_readonly;
2176
+ using Base::def_property_readonly_static;
2177
+ using Underlying = typename std::underlying_type<Type>::type;
2178
+ // Scalar is the integer representation of underlying type
2179
+ using Scalar = detail::conditional_t<detail::any_of<detail::is_std_char_type<Underlying>,
2180
+ std::is_same<Underlying, bool>>::value,
2181
+ detail::equivalent_integer_t<Underlying>,
2182
+ Underlying>;
2183
+
2184
+ template <typename... Extra>
2185
+ enum_(const handle &scope, const char *name, const Extra &...extra)
2186
+ : class_<Type>(scope, name, extra...), m_base(*this, scope) {
2187
+ constexpr bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>::value;
2188
+ constexpr bool is_convertible = std::is_convertible<Type, Underlying>::value;
2189
+ m_base.init(is_arithmetic, is_convertible);
2190
+
2191
+ def(init([](Scalar i) { return static_cast<Type>(i); }), arg("value"));
2192
+ def_property_readonly("value", [](Type value) { return (Scalar) value; });
2193
+ def("__int__", [](Type value) { return (Scalar) value; });
2194
+ def("__index__", [](Type value) { return (Scalar) value; });
2195
+ attr("__setstate__") = cpp_function(
2196
+ [](detail::value_and_holder &v_h, Scalar arg) {
2197
+ detail::initimpl::setstate<Base>(
2198
+ v_h, static_cast<Type>(arg), Py_TYPE(v_h.inst) != v_h.type->type);
2199
+ },
2200
+ detail::is_new_style_constructor(),
2201
+ pybind11::name("__setstate__"),
2202
+ is_method(*this),
2203
+ arg("state"));
2204
+ }
2205
+
2206
+ /// Export enumeration entries into the parent scope
2207
+ enum_ &export_values() {
2208
+ m_base.export_values();
2209
+ return *this;
2210
+ }
2211
+
2212
+ /// Add an enumeration entry
2213
+ enum_ &value(char const *name, Type value, const char *doc = nullptr) {
2214
+ m_base.value(name, pybind11::cast(value, return_value_policy::copy), doc);
2215
+ return *this;
2216
+ }
2217
+
2218
+ private:
2219
+ detail::enum_base m_base;
2220
+ };
2221
+
2222
+ PYBIND11_NAMESPACE_BEGIN(detail)
2223
+
2224
+ PYBIND11_NOINLINE void keep_alive_impl(handle nurse, handle patient) {
2225
+ if (!nurse || !patient) {
2226
+ pybind11_fail("Could not activate keep_alive!");
2227
+ }
2228
+
2229
+ if (patient.is_none() || nurse.is_none()) {
2230
+ return; /* Nothing to keep alive or nothing to be kept alive by */
2231
+ }
2232
+
2233
+ auto tinfo = all_type_info(Py_TYPE(nurse.ptr()));
2234
+ if (!tinfo.empty()) {
2235
+ /* It's a pybind-registered type, so we can store the patient in the
2236
+ * internal list. */
2237
+ add_patient(nurse.ptr(), patient.ptr());
2238
+ } else {
2239
+ /* Fall back to clever approach based on weak references taken from
2240
+ * Boost.Python. This is not used for pybind-registered types because
2241
+ * the objects can be destroyed out-of-order in a GC pass. */
2242
+ cpp_function disable_lifesupport([patient](handle weakref) {
2243
+ patient.dec_ref();
2244
+ weakref.dec_ref();
2245
+ });
2246
+
2247
+ weakref wr(nurse, disable_lifesupport);
2248
+
2249
+ patient.inc_ref(); /* reference patient and leak the weak reference */
2250
+ (void) wr.release();
2251
+ }
2252
+ }
2253
+
2254
+ PYBIND11_NOINLINE void
2255
+ keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret) {
2256
+ auto get_arg = [&](size_t n) {
2257
+ if (n == 0) {
2258
+ return ret;
2259
+ }
2260
+ if (n == 1 && call.init_self) {
2261
+ return call.init_self;
2262
+ }
2263
+ if (n <= call.args.size()) {
2264
+ return call.args[n - 1];
2265
+ }
2266
+ return handle();
2267
+ };
2268
+
2269
+ keep_alive_impl(get_arg(Nurse), get_arg(Patient));
2270
+ }
2271
+
2272
+ inline std::pair<decltype(internals::registered_types_py)::iterator, bool>
2273
+ all_type_info_get_cache(PyTypeObject *type) {
2274
+ auto res = get_internals()
2275
+ .registered_types_py
2276
+ #ifdef __cpp_lib_unordered_map_try_emplace
2277
+ .try_emplace(type);
2278
+ #else
2279
+ .emplace(type, std::vector<detail::type_info *>());
2280
+ #endif
2281
+ if (res.second) {
2282
+ // New cache entry created; set up a weak reference to automatically remove it if the type
2283
+ // gets destroyed:
2284
+ weakref((PyObject *) type, cpp_function([type](handle wr) {
2285
+ get_internals().registered_types_py.erase(type);
2286
+
2287
+ // TODO consolidate the erasure code in pybind11_meta_dealloc() in class.h
2288
+ auto &cache = get_internals().inactive_override_cache;
2289
+ for (auto it = cache.begin(), last = cache.end(); it != last;) {
2290
+ if (it->first == reinterpret_cast<PyObject *>(type)) {
2291
+ it = cache.erase(it);
2292
+ } else {
2293
+ ++it;
2294
+ }
2295
+ }
2296
+
2297
+ wr.dec_ref();
2298
+ }))
2299
+ .release();
2300
+ }
2301
+
2302
+ return res;
2303
+ }
2304
+
2305
+ /* There are a large number of apparently unused template arguments because
2306
+ * each combination requires a separate py::class_ registration.
2307
+ */
2308
+ template <typename Access,
2309
+ return_value_policy Policy,
2310
+ typename Iterator,
2311
+ typename Sentinel,
2312
+ typename ValueType,
2313
+ typename... Extra>
2314
+ struct iterator_state {
2315
+ Iterator it;
2316
+ Sentinel end;
2317
+ bool first_or_done;
2318
+ };
2319
+
2320
+ // Note: these helpers take the iterator by non-const reference because some
2321
+ // iterators in the wild can't be dereferenced when const. The & after Iterator
2322
+ // is required for MSVC < 16.9. SFINAE cannot be reused for result_type due to
2323
+ // bugs in ICC, NVCC, and PGI compilers. See PR #3293.
2324
+ template <typename Iterator, typename SFINAE = decltype(*std::declval<Iterator &>())>
2325
+ struct iterator_access {
2326
+ using result_type = decltype(*std::declval<Iterator &>());
2327
+ // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
2328
+ result_type operator()(Iterator &it) const { return *it; }
2329
+ };
2330
+
2331
+ template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).first)>
2332
+ class iterator_key_access {
2333
+ private:
2334
+ using pair_type = decltype(*std::declval<Iterator &>());
2335
+
2336
+ public:
2337
+ /* If either the pair itself or the element of the pair is a reference, we
2338
+ * want to return a reference, otherwise a value. When the decltype
2339
+ * expression is parenthesized it is based on the value category of the
2340
+ * expression; otherwise it is the declared type of the pair member.
2341
+ * The use of declval<pair_type> in the second branch rather than directly
2342
+ * using *std::declval<Iterator &>() is a workaround for nvcc
2343
+ * (it's not used in the first branch because going via decltype and back
2344
+ * through declval does not perfectly preserve references).
2345
+ */
2346
+ using result_type
2347
+ = conditional_t<std::is_reference<decltype(*std::declval<Iterator &>())>::value,
2348
+ decltype(((*std::declval<Iterator &>()).first)),
2349
+ decltype(std::declval<pair_type>().first)>;
2350
+ result_type operator()(Iterator &it) const { return (*it).first; }
2351
+ };
2352
+
2353
+ template <typename Iterator, typename SFINAE = decltype((*std::declval<Iterator &>()).second)>
2354
+ class iterator_value_access {
2355
+ private:
2356
+ using pair_type = decltype(*std::declval<Iterator &>());
2357
+
2358
+ public:
2359
+ using result_type
2360
+ = conditional_t<std::is_reference<decltype(*std::declval<Iterator &>())>::value,
2361
+ decltype(((*std::declval<Iterator &>()).second)),
2362
+ decltype(std::declval<pair_type>().second)>;
2363
+ result_type operator()(Iterator &it) const { return (*it).second; }
2364
+ };
2365
+
2366
+ template <typename Access,
2367
+ return_value_policy Policy,
2368
+ typename Iterator,
2369
+ typename Sentinel,
2370
+ typename ValueType,
2371
+ typename... Extra>
2372
+ iterator make_iterator_impl(Iterator first, Sentinel last, Extra &&...extra) {
2373
+ using state = detail::iterator_state<Access, Policy, Iterator, Sentinel, ValueType, Extra...>;
2374
+ // TODO: state captures only the types of Extra, not the values
2375
+
2376
+ if (!detail::get_type_info(typeid(state), false)) {
2377
+ class_<state>(handle(), "iterator", pybind11::module_local())
2378
+ .def("__iter__", [](state &s) -> state & { return s; })
2379
+ .def(
2380
+ "__next__",
2381
+ [](state &s) -> ValueType {
2382
+ if (!s.first_or_done) {
2383
+ ++s.it;
2384
+ } else {
2385
+ s.first_or_done = false;
2386
+ }
2387
+ if (s.it == s.end) {
2388
+ s.first_or_done = true;
2389
+ throw stop_iteration();
2390
+ }
2391
+ return Access()(s.it);
2392
+ // NOLINTNEXTLINE(readability-const-return-type) // PR #3263
2393
+ },
2394
+ std::forward<Extra>(extra)...,
2395
+ Policy);
2396
+ }
2397
+
2398
+ return cast(state{first, last, true});
2399
+ }
2400
+
2401
+ PYBIND11_NAMESPACE_END(detail)
2402
+
2403
+ /// Makes a python iterator from a first and past-the-end C++ InputIterator.
2404
+ template <return_value_policy Policy = return_value_policy::reference_internal,
2405
+ typename Iterator,
2406
+ typename Sentinel,
2407
+ typename ValueType = typename detail::iterator_access<Iterator>::result_type,
2408
+ typename... Extra>
2409
+ iterator make_iterator(Iterator first, Sentinel last, Extra &&...extra) {
2410
+ return detail::make_iterator_impl<detail::iterator_access<Iterator>,
2411
+ Policy,
2412
+ Iterator,
2413
+ Sentinel,
2414
+ ValueType,
2415
+ Extra...>(first, last, std::forward<Extra>(extra)...);
2416
+ }
2417
+
2418
+ /// Makes a python iterator over the keys (`.first`) of a iterator over pairs from a
2419
+ /// first and past-the-end InputIterator.
2420
+ template <return_value_policy Policy = return_value_policy::reference_internal,
2421
+ typename Iterator,
2422
+ typename Sentinel,
2423
+ typename KeyType = typename detail::iterator_key_access<Iterator>::result_type,
2424
+ typename... Extra>
2425
+ iterator make_key_iterator(Iterator first, Sentinel last, Extra &&...extra) {
2426
+ return detail::make_iterator_impl<detail::iterator_key_access<Iterator>,
2427
+ Policy,
2428
+ Iterator,
2429
+ Sentinel,
2430
+ KeyType,
2431
+ Extra...>(first, last, std::forward<Extra>(extra)...);
2432
+ }
2433
+
2434
+ /// Makes a python iterator over the values (`.second`) of a iterator over pairs from a
2435
+ /// first and past-the-end InputIterator.
2436
+ template <return_value_policy Policy = return_value_policy::reference_internal,
2437
+ typename Iterator,
2438
+ typename Sentinel,
2439
+ typename ValueType = typename detail::iterator_value_access<Iterator>::result_type,
2440
+ typename... Extra>
2441
+ iterator make_value_iterator(Iterator first, Sentinel last, Extra &&...extra) {
2442
+ return detail::make_iterator_impl<detail::iterator_value_access<Iterator>,
2443
+ Policy,
2444
+ Iterator,
2445
+ Sentinel,
2446
+ ValueType,
2447
+ Extra...>(first, last, std::forward<Extra>(extra)...);
2448
+ }
2449
+
2450
+ /// Makes an iterator over values of an stl container or other container supporting
2451
+ /// `std::begin()`/`std::end()`
2452
+ template <return_value_policy Policy = return_value_policy::reference_internal,
2453
+ typename Type,
2454
+ typename... Extra>
2455
+ iterator make_iterator(Type &value, Extra &&...extra) {
2456
+ return make_iterator<Policy>(
2457
+ std::begin(value), std::end(value), std::forward<Extra>(extra)...);
2458
+ }
2459
+
2460
+ /// Makes an iterator over the keys (`.first`) of a stl map-like container supporting
2461
+ /// `std::begin()`/`std::end()`
2462
+ template <return_value_policy Policy = return_value_policy::reference_internal,
2463
+ typename Type,
2464
+ typename... Extra>
2465
+ iterator make_key_iterator(Type &value, Extra &&...extra) {
2466
+ return make_key_iterator<Policy>(
2467
+ std::begin(value), std::end(value), std::forward<Extra>(extra)...);
2468
+ }
2469
+
2470
+ /// Makes an iterator over the values (`.second`) of a stl map-like container supporting
2471
+ /// `std::begin()`/`std::end()`
2472
+ template <return_value_policy Policy = return_value_policy::reference_internal,
2473
+ typename Type,
2474
+ typename... Extra>
2475
+ iterator make_value_iterator(Type &value, Extra &&...extra) {
2476
+ return make_value_iterator<Policy>(
2477
+ std::begin(value), std::end(value), std::forward<Extra>(extra)...);
2478
+ }
2479
+
2480
+ template <typename InputType, typename OutputType>
2481
+ void implicitly_convertible() {
2482
+ struct set_flag {
2483
+ bool &flag;
2484
+ explicit set_flag(bool &flag_) : flag(flag_) { flag_ = true; }
2485
+ ~set_flag() { flag = false; }
2486
+ };
2487
+ auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * {
2488
+ static bool currently_used = false;
2489
+ if (currently_used) { // implicit conversions are non-reentrant
2490
+ return nullptr;
2491
+ }
2492
+ set_flag flag_helper(currently_used);
2493
+ if (!detail::make_caster<InputType>().load(obj, false)) {
2494
+ return nullptr;
2495
+ }
2496
+ tuple args(1);
2497
+ args[0] = obj;
2498
+ PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr);
2499
+ if (result == nullptr) {
2500
+ PyErr_Clear();
2501
+ }
2502
+ return result;
2503
+ };
2504
+
2505
+ if (auto *tinfo = detail::get_type_info(typeid(OutputType))) {
2506
+ tinfo->implicit_conversions.emplace_back(std::move(implicit_caster));
2507
+ } else {
2508
+ pybind11_fail("implicitly_convertible: Unable to find type " + type_id<OutputType>());
2509
+ }
2510
+ }
2511
+
2512
+ inline void register_exception_translator(ExceptionTranslator &&translator) {
2513
+ detail::get_internals().registered_exception_translators.push_front(
2514
+ std::forward<ExceptionTranslator>(translator));
2515
+ }
2516
+
2517
+ /**
2518
+ * Add a new module-local exception translator. Locally registered functions
2519
+ * will be tried before any globally registered exception translators, which
2520
+ * will only be invoked if the module-local handlers do not deal with
2521
+ * the exception.
2522
+ */
2523
+ inline void register_local_exception_translator(ExceptionTranslator &&translator) {
2524
+ detail::get_local_internals().registered_exception_translators.push_front(
2525
+ std::forward<ExceptionTranslator>(translator));
2526
+ }
2527
+
2528
+ /**
2529
+ * Wrapper to generate a new Python exception type.
2530
+ *
2531
+ * This should only be used with PyErr_SetString for now.
2532
+ * It is not (yet) possible to use as a py::base.
2533
+ * Template type argument is reserved for future use.
2534
+ */
2535
+ template <typename type>
2536
+ class exception : public object {
2537
+ public:
2538
+ exception() = default;
2539
+ exception(handle scope, const char *name, handle base = PyExc_Exception) {
2540
+ std::string full_name
2541
+ = scope.attr("__name__").cast<std::string>() + std::string(".") + name;
2542
+ m_ptr = PyErr_NewException(const_cast<char *>(full_name.c_str()), base.ptr(), nullptr);
2543
+ if (hasattr(scope, "__dict__") && scope.attr("__dict__").contains(name)) {
2544
+ pybind11_fail("Error during initialization: multiple incompatible "
2545
+ "definitions with name \""
2546
+ + std::string(name) + "\"");
2547
+ }
2548
+ scope.attr(name) = *this;
2549
+ }
2550
+
2551
+ // Sets the current python exception to this exception object with the given message
2552
+ void operator()(const char *message) { PyErr_SetString(m_ptr, message); }
2553
+ };
2554
+
2555
+ PYBIND11_NAMESPACE_BEGIN(detail)
2556
+ // Returns a reference to a function-local static exception object used in the simple
2557
+ // register_exception approach below. (It would be simpler to have the static local variable
2558
+ // directly in register_exception, but that makes clang <3.5 segfault - issue #1349).
2559
+ template <typename CppException>
2560
+ exception<CppException> &get_exception_object() {
2561
+ static exception<CppException> ex;
2562
+ return ex;
2563
+ }
2564
+
2565
+ // Helper function for register_exception and register_local_exception
2566
+ template <typename CppException>
2567
+ exception<CppException> &
2568
+ register_exception_impl(handle scope, const char *name, handle base, bool isLocal) {
2569
+ auto &ex = detail::get_exception_object<CppException>();
2570
+ if (!ex) {
2571
+ ex = exception<CppException>(scope, name, base);
2572
+ }
2573
+
2574
+ auto register_func
2575
+ = isLocal ? &register_local_exception_translator : &register_exception_translator;
2576
+
2577
+ register_func([](std::exception_ptr p) {
2578
+ if (!p) {
2579
+ return;
2580
+ }
2581
+ try {
2582
+ std::rethrow_exception(p);
2583
+ } catch (const CppException &e) {
2584
+ detail::get_exception_object<CppException>()(e.what());
2585
+ }
2586
+ });
2587
+ return ex;
2588
+ }
2589
+
2590
+ PYBIND11_NAMESPACE_END(detail)
2591
+
2592
+ /**
2593
+ * Registers a Python exception in `m` of the given `name` and installs a translator to
2594
+ * translate the C++ exception to the created Python exception using the what() method.
2595
+ * This is intended for simple exception translations; for more complex translation, register the
2596
+ * exception object and translator directly.
2597
+ */
2598
+ template <typename CppException>
2599
+ exception<CppException> &
2600
+ register_exception(handle scope, const char *name, handle base = PyExc_Exception) {
2601
+ return detail::register_exception_impl<CppException>(scope, name, base, false /* isLocal */);
2602
+ }
2603
+
2604
+ /**
2605
+ * Registers a Python exception in `m` of the given `name` and installs a translator to
2606
+ * translate the C++ exception to the created Python exception using the what() method.
2607
+ * This translator will only be used for exceptions that are thrown in this module and will be
2608
+ * tried before global exception translators, including those registered with register_exception.
2609
+ * This is intended for simple exception translations; for more complex translation, register the
2610
+ * exception object and translator directly.
2611
+ */
2612
+ template <typename CppException>
2613
+ exception<CppException> &
2614
+ register_local_exception(handle scope, const char *name, handle base = PyExc_Exception) {
2615
+ return detail::register_exception_impl<CppException>(scope, name, base, true /* isLocal */);
2616
+ }
2617
+
2618
+ PYBIND11_NAMESPACE_BEGIN(detail)
2619
+ PYBIND11_NOINLINE void print(const tuple &args, const dict &kwargs) {
2620
+ auto strings = tuple(args.size());
2621
+ for (size_t i = 0; i < args.size(); ++i) {
2622
+ strings[i] = str(args[i]);
2623
+ }
2624
+ auto sep = kwargs.contains("sep") ? kwargs["sep"] : str(" ");
2625
+ auto line = sep.attr("join")(std::move(strings));
2626
+
2627
+ object file;
2628
+ if (kwargs.contains("file")) {
2629
+ file = kwargs["file"].cast<object>();
2630
+ } else {
2631
+ try {
2632
+ file = module_::import("sys").attr("stdout");
2633
+ } catch (const error_already_set &) {
2634
+ /* If print() is called from code that is executed as
2635
+ part of garbage collection during interpreter shutdown,
2636
+ importing 'sys' can fail. Give up rather than crashing the
2637
+ interpreter in this case. */
2638
+ return;
2639
+ }
2640
+ }
2641
+
2642
+ auto write = file.attr("write");
2643
+ write(std::move(line));
2644
+ write(kwargs.contains("end") ? kwargs["end"] : str("\n"));
2645
+
2646
+ if (kwargs.contains("flush") && kwargs["flush"].cast<bool>()) {
2647
+ file.attr("flush")();
2648
+ }
2649
+ }
2650
+ PYBIND11_NAMESPACE_END(detail)
2651
+
2652
+ template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
2653
+ void print(Args &&...args) {
2654
+ auto c = detail::collect_arguments<policy>(std::forward<Args>(args)...);
2655
+ detail::print(c.args(), c.kwargs());
2656
+ }
2657
+
2658
+ inline void
2659
+ error_already_set::m_fetched_error_deleter(detail::error_fetch_and_normalize *raw_ptr) {
2660
+ gil_scoped_acquire gil;
2661
+ error_scope scope;
2662
+ delete raw_ptr;
2663
+ }
2664
+
2665
+ inline const char *error_already_set::what() const noexcept {
2666
+ gil_scoped_acquire gil;
2667
+ error_scope scope;
2668
+ return m_fetched_error->error_string().c_str();
2669
+ }
2670
+
2671
+ PYBIND11_NAMESPACE_BEGIN(detail)
2672
+
2673
+ inline function
2674
+ get_type_override(const void *this_ptr, const type_info *this_type, const char *name) {
2675
+ handle self = get_object_handle(this_ptr, this_type);
2676
+ if (!self) {
2677
+ return function();
2678
+ }
2679
+ handle type = type::handle_of(self);
2680
+ auto key = std::make_pair(type.ptr(), name);
2681
+
2682
+ /* Cache functions that aren't overridden in Python to avoid
2683
+ many costly Python dictionary lookups below */
2684
+ auto &cache = get_internals().inactive_override_cache;
2685
+ if (cache.find(key) != cache.end()) {
2686
+ return function();
2687
+ }
2688
+
2689
+ function override = getattr(self, name, function());
2690
+ if (override.is_cpp_function()) {
2691
+ cache.insert(std::move(key));
2692
+ return function();
2693
+ }
2694
+
2695
+ /* Don't call dispatch code if invoked from overridden function.
2696
+ Unfortunately this doesn't work on PyPy. */
2697
+ #if !defined(PYPY_VERSION)
2698
+ # if PY_VERSION_HEX >= 0x03090000
2699
+ PyFrameObject *frame = PyThreadState_GetFrame(PyThreadState_Get());
2700
+ if (frame != nullptr) {
2701
+ PyCodeObject *f_code = PyFrame_GetCode(frame);
2702
+ // f_code is guaranteed to not be NULL
2703
+ if ((std::string) str(f_code->co_name) == name && f_code->co_argcount > 0) {
2704
+ PyObject *locals = PyEval_GetLocals();
2705
+ if (locals != nullptr) {
2706
+ PyObject *co_varnames = PyObject_GetAttrString((PyObject *) f_code, "co_varnames");
2707
+ PyObject *self_arg = PyTuple_GET_ITEM(co_varnames, 0);
2708
+ Py_DECREF(co_varnames);
2709
+ PyObject *self_caller = dict_getitem(locals, self_arg);
2710
+ if (self_caller == self.ptr()) {
2711
+ Py_DECREF(f_code);
2712
+ Py_DECREF(frame);
2713
+ return function();
2714
+ }
2715
+ }
2716
+ }
2717
+ Py_DECREF(f_code);
2718
+ Py_DECREF(frame);
2719
+ }
2720
+ # else
2721
+ PyFrameObject *frame = PyThreadState_Get()->frame;
2722
+ if (frame != nullptr && (std::string) str(frame->f_code->co_name) == name
2723
+ && frame->f_code->co_argcount > 0) {
2724
+ PyFrame_FastToLocals(frame);
2725
+ PyObject *self_caller
2726
+ = dict_getitem(frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
2727
+ if (self_caller == self.ptr()) {
2728
+ return function();
2729
+ }
2730
+ }
2731
+ # endif
2732
+
2733
+ #else
2734
+ /* PyPy currently doesn't provide a detailed cpyext emulation of
2735
+ frame objects, so we have to emulate this using Python. This
2736
+ is going to be slow..*/
2737
+ dict d;
2738
+ d["self"] = self;
2739
+ d["name"] = pybind11::str(name);
2740
+ PyObject *result
2741
+ = PyRun_String("import inspect\n"
2742
+ "frame = inspect.currentframe()\n"
2743
+ "if frame is not None:\n"
2744
+ " frame = frame.f_back\n"
2745
+ " if frame is not None and str(frame.f_code.co_name) == name and "
2746
+ "frame.f_code.co_argcount > 0:\n"
2747
+ " self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n"
2748
+ " if self_caller == self:\n"
2749
+ " self = None\n",
2750
+ Py_file_input,
2751
+ d.ptr(),
2752
+ d.ptr());
2753
+ if (result == nullptr)
2754
+ throw error_already_set();
2755
+ Py_DECREF(result);
2756
+ if (d["self"].is_none())
2757
+ return function();
2758
+ #endif
2759
+
2760
+ return override;
2761
+ }
2762
+ PYBIND11_NAMESPACE_END(detail)
2763
+
2764
+ /** \rst
2765
+ Try to retrieve a python method by the provided name from the instance pointed to by the
2766
+ this_ptr.
2767
+
2768
+ :this_ptr: The pointer to the object the overridden method should be retrieved for. This should
2769
+ be the first non-trampoline class encountered in the inheritance chain.
2770
+ :name: The name of the overridden Python method to retrieve.
2771
+ :return: The Python method by this name from the object or an empty function wrapper.
2772
+ \endrst */
2773
+ template <class T>
2774
+ function get_override(const T *this_ptr, const char *name) {
2775
+ auto *tinfo = detail::get_type_info(typeid(T));
2776
+ return tinfo ? detail::get_type_override(this_ptr, tinfo, name) : function();
2777
+ }
2778
+
2779
+ #define PYBIND11_OVERRIDE_IMPL(ret_type, cname, name, ...) \
2780
+ do { \
2781
+ pybind11::gil_scoped_acquire gil; \
2782
+ pybind11::function override \
2783
+ = pybind11::get_override(static_cast<const cname *>(this), name); \
2784
+ if (override) { \
2785
+ auto o = override(__VA_ARGS__); \
2786
+ if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) { \
2787
+ static pybind11::detail::override_caster_t<ret_type> caster; \
2788
+ return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \
2789
+ } \
2790
+ return pybind11::detail::cast_safe<ret_type>(std::move(o)); \
2791
+ } \
2792
+ } while (false)
2793
+
2794
+ /** \rst
2795
+ Macro to populate the virtual method in the trampoline class. This macro tries to look up a
2796
+ method named 'fn' from the Python side, deals with the :ref:`gil` and necessary argument
2797
+ conversions to call this method and return the appropriate type.
2798
+ See :ref:`overriding_virtuals` for more information. This macro should be used when the method
2799
+ name in C is not the same as the method name in Python. For example with `__str__`.
2800
+
2801
+ .. code-block:: cpp
2802
+
2803
+ std::string toString() override {
2804
+ PYBIND11_OVERRIDE_NAME(
2805
+ std::string, // Return type (ret_type)
2806
+ Animal, // Parent class (cname)
2807
+ "__str__", // Name of method in Python (name)
2808
+ toString, // Name of function in C++ (fn)
2809
+ );
2810
+ }
2811
+ \endrst */
2812
+ #define PYBIND11_OVERRIDE_NAME(ret_type, cname, name, fn, ...) \
2813
+ do { \
2814
+ PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
2815
+ return cname::fn(__VA_ARGS__); \
2816
+ } while (false)
2817
+
2818
+ /** \rst
2819
+ Macro for pure virtual functions, this function is identical to
2820
+ :c:macro:`PYBIND11_OVERRIDE_NAME`, except that it throws if no override can be found.
2821
+ \endrst */
2822
+ #define PYBIND11_OVERRIDE_PURE_NAME(ret_type, cname, name, fn, ...) \
2823
+ do { \
2824
+ PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
2825
+ pybind11::pybind11_fail( \
2826
+ "Tried to call pure virtual function \"" PYBIND11_STRINGIFY(cname) "::" name "\""); \
2827
+ } while (false)
2828
+
2829
+ /** \rst
2830
+ Macro to populate the virtual method in the trampoline class. This macro tries to look up the
2831
+ method from the Python side, deals with the :ref:`gil` and necessary argument conversions to
2832
+ call this method and return the appropriate type. This macro should be used if the method name
2833
+ in C and in Python are identical.
2834
+ See :ref:`overriding_virtuals` for more information.
2835
+
2836
+ .. code-block:: cpp
2837
+
2838
+ class PyAnimal : public Animal {
2839
+ public:
2840
+ // Inherit the constructors
2841
+ using Animal::Animal;
2842
+
2843
+ // Trampoline (need one for each virtual function)
2844
+ std::string go(int n_times) override {
2845
+ PYBIND11_OVERRIDE_PURE(
2846
+ std::string, // Return type (ret_type)
2847
+ Animal, // Parent class (cname)
2848
+ go, // Name of function in C++ (must match Python name) (fn)
2849
+ n_times // Argument(s) (...)
2850
+ );
2851
+ }
2852
+ };
2853
+ \endrst */
2854
+ #define PYBIND11_OVERRIDE(ret_type, cname, fn, ...) \
2855
+ PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
2856
+
2857
+ /** \rst
2858
+ Macro for pure virtual functions, this function is identical to :c:macro:`PYBIND11_OVERRIDE`,
2859
+ except that it throws if no override can be found.
2860
+ \endrst */
2861
+ #define PYBIND11_OVERRIDE_PURE(ret_type, cname, fn, ...) \
2862
+ PYBIND11_OVERRIDE_PURE_NAME( \
2863
+ PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
2864
+
2865
+ // Deprecated versions
2866
+
2867
+ PYBIND11_DEPRECATED("get_type_overload has been deprecated")
2868
+ inline function
2869
+ get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name) {
2870
+ return detail::get_type_override(this_ptr, this_type, name);
2871
+ }
2872
+
2873
+ template <class T>
2874
+ inline function get_overload(const T *this_ptr, const char *name) {
2875
+ return get_override(this_ptr, name);
2876
+ }
2877
+
2878
+ #define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) \
2879
+ PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__)
2880
+ #define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
2881
+ PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__)
2882
+ #define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
2883
+ PYBIND11_OVERRIDE_PURE_NAME( \
2884
+ PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__);
2885
+ #define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
2886
+ PYBIND11_OVERRIDE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__)
2887
+ #define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
2888
+ PYBIND11_OVERRIDE_PURE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__);
2889
+
2890
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)