ctpbee-opt-api 0.1.0__cp312-cp312-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.cp312-win_amd64.pyd +0 -0
  160. ctpbee_api/ctp/vnctptd.cp312-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.cp312-win_amd64.pyd +0 -0
  281. ctpbee_api/ctp_mini/vnctp_minitd.cp312-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.cp312-win_amd64.pyd +0 -0
  410. ctpbee_api/rohon/vnrohontd.cp312-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,1965 @@
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
+ #if defined(_MSC_VER)
14
+ # pragma warning(push)
15
+ # pragma warning(disable: 4100) // warning C4100: Unreferenced formal parameter
16
+ # pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
17
+ # pragma warning(disable: 4512) // warning C4512: Assignment operator was implicitly defined as deleted
18
+ # pragma warning(disable: 4800) // warning C4800: 'int': forcing value to bool 'true' or 'false' (performance warning)
19
+ # pragma warning(disable: 4996) // warning C4996: The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name
20
+ # pragma warning(disable: 4702) // warning C4702: unreachable code
21
+ # pragma warning(disable: 4522) // warning C4522: multiple assignment operators specified
22
+ #elif defined(__INTEL_COMPILER)
23
+ # pragma warning(push)
24
+ # pragma warning(disable: 68) // integer conversion resulted in a change of sign
25
+ # pragma warning(disable: 186) // pointless comparison of unsigned integer with zero
26
+ # pragma warning(disable: 878) // incompatible exception specifications
27
+ # pragma warning(disable: 1334) // the "template" keyword used for syntactic disambiguation may only be used within a template
28
+ # pragma warning(disable: 1682) // implicit conversion of a 64-bit integral type to a smaller integral type (potential portability problem)
29
+ # pragma warning(disable: 1875) // offsetof applied to non-POD (Plain Old Data) types is nonstandard
30
+ # pragma warning(disable: 2196) // warning #2196: routine is both "inline" and "noinline"
31
+ #elif defined(__GNUG__) && !defined(__clang__)
32
+ # pragma GCC diagnostic push
33
+ # pragma GCC diagnostic ignored "-Wunused-but-set-parameter"
34
+ # pragma GCC diagnostic ignored "-Wunused-but-set-variable"
35
+ # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
36
+ # pragma GCC diagnostic ignored "-Wstrict-aliasing"
37
+ # pragma GCC diagnostic ignored "-Wattributes"
38
+ # if __GNUC__ >= 7
39
+ # pragma GCC diagnostic ignored "-Wnoexcept-type"
40
+ # endif
41
+ #endif
42
+
43
+ #include "attr.h"
44
+ #include "options.h"
45
+ #include "detail/class.h"
46
+ #include "detail/init.h"
47
+
48
+ NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
49
+
50
+ /// Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object
51
+ class cpp_function : public function {
52
+ public:
53
+ cpp_function() { }
54
+
55
+ /// Construct a cpp_function from a vanilla function pointer
56
+ template <typename Return, typename... Args, typename... Extra>
57
+ cpp_function(Return (*f)(Args...), const Extra&... extra) {
58
+ initialize(f, f, extra...);
59
+ }
60
+
61
+ /// Construct a cpp_function from a lambda function (possibly with internal state)
62
+ template <typename Func, typename... Extra,
63
+ typename = detail::enable_if_t<detail::is_lambda<Func>::value>>
64
+ cpp_function(Func &&f, const Extra&... extra) {
65
+ initialize(std::forward<Func>(f),
66
+ (detail::function_signature_t<Func> *) nullptr, extra...);
67
+ }
68
+
69
+ /// Construct a cpp_function from a class method (non-const)
70
+ template <typename Return, typename Class, typename... Arg, typename... Extra>
71
+ cpp_function(Return (Class::*f)(Arg...), const Extra&... extra) {
72
+ initialize([f](Class *c, Arg... args) -> Return { return (c->*f)(args...); },
73
+ (Return (*) (Class *, Arg...)) nullptr, extra...);
74
+ }
75
+
76
+ /// Construct a cpp_function from a class method (const)
77
+ template <typename Return, typename Class, typename... Arg, typename... Extra>
78
+ cpp_function(Return (Class::*f)(Arg...) const, const Extra&... extra) {
79
+ initialize([f](const Class *c, Arg... args) -> Return { return (c->*f)(args...); },
80
+ (Return (*)(const Class *, Arg ...)) nullptr, extra...);
81
+ }
82
+
83
+ /// Return the function name
84
+ object name() const { return attr("__name__"); }
85
+
86
+ protected:
87
+ /// Space optimization: don't inline this frequently instantiated fragment
88
+ PYBIND11_NOINLINE detail::function_record *make_function_record() {
89
+ return new detail::function_record();
90
+ }
91
+
92
+ /// Special internal constructor for functors, lambda functions, etc.
93
+ template <typename Func, typename Return, typename... Args, typename... Extra>
94
+ void initialize(Func &&f, Return (*)(Args...), const Extra&... extra) {
95
+ using namespace detail;
96
+
97
+ struct capture { remove_reference_t<Func> f; };
98
+
99
+ /* Store the function including any extra state it might have (e.g. a lambda capture object) */
100
+ auto rec = make_function_record();
101
+
102
+ /* Store the capture object directly in the function record if there is enough space */
103
+ if (sizeof(capture) <= sizeof(rec->data)) {
104
+ /* Without these pragmas, GCC warns that there might not be
105
+ enough space to use the placement new operator. However, the
106
+ 'if' statement above ensures that this is the case. */
107
+ #if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
108
+ # pragma GCC diagnostic push
109
+ # pragma GCC diagnostic ignored "-Wplacement-new"
110
+ #endif
111
+ new ((capture *) &rec->data) capture { std::forward<Func>(f) };
112
+ #if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
113
+ # pragma GCC diagnostic pop
114
+ #endif
115
+ if (!std::is_trivially_destructible<Func>::value)
116
+ rec->free_data = [](function_record *r) { ((capture *) &r->data)->~capture(); };
117
+ } else {
118
+ rec->data[0] = new capture { std::forward<Func>(f) };
119
+ rec->free_data = [](function_record *r) { delete ((capture *) r->data[0]); };
120
+ }
121
+
122
+ /* Type casters for the function arguments and return value */
123
+ using cast_in = argument_loader<Args...>;
124
+ using cast_out = make_caster<
125
+ conditional_t<std::is_void<Return>::value, void_type, Return>
126
+ >;
127
+
128
+ static_assert(expected_num_args<Extra...>(sizeof...(Args), cast_in::has_args, cast_in::has_kwargs),
129
+ "The number of argument annotations does not match the number of function arguments");
130
+
131
+ /* Dispatch code which converts function arguments and performs the actual function call */
132
+ rec->impl = [](function_call &call) -> handle {
133
+ cast_in args_converter;
134
+
135
+ /* Try to cast the function arguments into the C++ domain */
136
+ if (!args_converter.load_args(call))
137
+ return PYBIND11_TRY_NEXT_OVERLOAD;
138
+
139
+ /* Invoke call policy pre-call hook */
140
+ process_attributes<Extra...>::precall(call);
141
+
142
+ /* Get a pointer to the capture object */
143
+ auto data = (sizeof(capture) <= sizeof(call.func.data)
144
+ ? &call.func.data : call.func.data[0]);
145
+ capture *cap = const_cast<capture *>(reinterpret_cast<const capture *>(data));
146
+
147
+ /* Override policy for rvalues -- usually to enforce rvp::move on an rvalue */
148
+ return_value_policy policy = return_value_policy_override<Return>::policy(call.func.policy);
149
+
150
+ /* Function scope guard -- defaults to the compile-to-nothing `void_type` */
151
+ using Guard = extract_guard_t<Extra...>;
152
+
153
+ /* Perform the function call */
154
+ handle result = cast_out::cast(
155
+ std::move(args_converter).template call<Return, Guard>(cap->f), policy, call.parent);
156
+
157
+ /* Invoke call policy post-call hook */
158
+ process_attributes<Extra...>::postcall(call, result);
159
+
160
+ return result;
161
+ };
162
+
163
+ /* Process any user-provided function attributes */
164
+ process_attributes<Extra...>::init(extra..., rec);
165
+
166
+ /* Generate a readable signature describing the function's arguments and return value types */
167
+ PYBIND11_DESCR signature = _("(") + cast_in::arg_names() + _(") -> ") + cast_out::name();
168
+
169
+ /* Register the function with Python from generic (non-templated) code */
170
+ initialize_generic(rec, signature.text(), signature.types(), sizeof...(Args));
171
+
172
+ if (cast_in::has_args) rec->has_args = true;
173
+ if (cast_in::has_kwargs) rec->has_kwargs = true;
174
+
175
+ /* Stash some additional information used by an important optimization in 'functional.h' */
176
+ using FunctionType = Return (*)(Args...);
177
+ constexpr bool is_function_ptr =
178
+ std::is_convertible<Func, FunctionType>::value &&
179
+ sizeof(capture) == sizeof(void *);
180
+ if (is_function_ptr) {
181
+ rec->is_stateless = true;
182
+ rec->data[1] = const_cast<void *>(reinterpret_cast<const void *>(&typeid(FunctionType)));
183
+ }
184
+ }
185
+
186
+ /// Register a function call with Python (generic non-templated code goes here)
187
+ void initialize_generic(detail::function_record *rec, const char *text,
188
+ const std::type_info *const *types, size_t args) {
189
+
190
+ /* Create copies of all referenced C-style strings */
191
+ rec->name = strdup(rec->name ? rec->name : "");
192
+ if (rec->doc) rec->doc = strdup(rec->doc);
193
+ for (auto &a: rec->args) {
194
+ if (a.name)
195
+ a.name = strdup(a.name);
196
+ if (a.descr)
197
+ a.descr = strdup(a.descr);
198
+ else if (a.value)
199
+ a.descr = strdup(a.value.attr("__repr__")().cast<std::string>().c_str());
200
+ }
201
+
202
+ rec->is_constructor = !strcmp(rec->name, "__init__") || !strcmp(rec->name, "__setstate__");
203
+
204
+ #if !defined(NDEBUG) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING)
205
+ if (rec->is_constructor && !rec->is_new_style_constructor) {
206
+ const auto class_name = std::string(((PyTypeObject *) rec->scope.ptr())->tp_name);
207
+ const auto func_name = std::string(rec->name);
208
+ PyErr_WarnEx(
209
+ PyExc_FutureWarning,
210
+ ("pybind11-bound class '" + class_name + "' is using an old-style "
211
+ "placement-new '" + func_name + "' which has been deprecated. See "
212
+ "the upgrade guide in pybind11's docs. This message is only visible "
213
+ "when compiled in debug mode.").c_str(), 0
214
+ );
215
+ }
216
+ #endif
217
+
218
+ /* Generate a proper function signature */
219
+ std::string signature;
220
+ size_t type_depth = 0, char_index = 0, type_index = 0, arg_index = 0;
221
+ while (true) {
222
+ char c = text[char_index++];
223
+ if (c == '\0')
224
+ break;
225
+
226
+ if (c == '{') {
227
+ // Write arg name for everything except *args, **kwargs and return type.
228
+ if (type_depth == 0 && text[char_index] != '*' && arg_index < args) {
229
+ if (!rec->args.empty() && rec->args[arg_index].name) {
230
+ signature += rec->args[arg_index].name;
231
+ } else if (arg_index == 0 && rec->is_method) {
232
+ signature += "self";
233
+ } else {
234
+ signature += "arg" + std::to_string(arg_index - (rec->is_method ? 1 : 0));
235
+ }
236
+ signature += ": ";
237
+ }
238
+ ++type_depth;
239
+ } else if (c == '}') {
240
+ --type_depth;
241
+ if (type_depth == 0) {
242
+ if (arg_index < rec->args.size() && rec->args[arg_index].descr) {
243
+ signature += "=";
244
+ signature += rec->args[arg_index].descr;
245
+ }
246
+ arg_index++;
247
+ }
248
+ } else if (c == '%') {
249
+ const std::type_info *t = types[type_index++];
250
+ if (!t)
251
+ pybind11_fail("Internal error while parsing type signature (1)");
252
+ if (auto tinfo = detail::get_type_info(*t)) {
253
+ handle th((PyObject *) tinfo->type);
254
+ signature +=
255
+ th.attr("__module__").cast<std::string>() + "." +
256
+ th.attr("__qualname__").cast<std::string>(); // Python 3.3+, but we backport it to earlier versions
257
+ } else if (rec->is_new_style_constructor && arg_index == 0) {
258
+ // A new-style `__init__` takes `self` as `value_and_holder`.
259
+ // Rewrite it to the proper class type.
260
+ signature +=
261
+ rec->scope.attr("__module__").cast<std::string>() + "." +
262
+ rec->scope.attr("__qualname__").cast<std::string>();
263
+ } else {
264
+ std::string tname(t->name());
265
+ detail::clean_type_id(tname);
266
+ signature += tname;
267
+ }
268
+ } else {
269
+ signature += c;
270
+ }
271
+ }
272
+ if (type_depth != 0 || types[type_index] != nullptr)
273
+ pybind11_fail("Internal error while parsing type signature (2)");
274
+
275
+ #if !defined(PYBIND11_CONSTEXPR_DESCR)
276
+ delete[] types;
277
+ delete[] text;
278
+ #endif
279
+
280
+ #if PY_MAJOR_VERSION < 3
281
+ if (strcmp(rec->name, "__next__") == 0) {
282
+ std::free(rec->name);
283
+ rec->name = strdup("next");
284
+ } else if (strcmp(rec->name, "__bool__") == 0) {
285
+ std::free(rec->name);
286
+ rec->name = strdup("__nonzero__");
287
+ }
288
+ #endif
289
+ rec->signature = strdup(signature.c_str());
290
+ rec->args.shrink_to_fit();
291
+ rec->nargs = (std::uint16_t) args;
292
+
293
+ if (rec->sibling && PYBIND11_INSTANCE_METHOD_CHECK(rec->sibling.ptr()))
294
+ rec->sibling = PYBIND11_INSTANCE_METHOD_GET_FUNCTION(rec->sibling.ptr());
295
+
296
+ detail::function_record *chain = nullptr, *chain_start = rec;
297
+ if (rec->sibling) {
298
+ if (PyCFunction_Check(rec->sibling.ptr())) {
299
+ auto rec_capsule = reinterpret_borrow<capsule>(PyCFunction_GET_SELF(rec->sibling.ptr()));
300
+ chain = (detail::function_record *) rec_capsule;
301
+ /* Never append a method to an overload chain of a parent class;
302
+ instead, hide the parent's overloads in this case */
303
+ if (!chain->scope.is(rec->scope))
304
+ chain = nullptr;
305
+ }
306
+ // Don't trigger for things like the default __init__, which are wrapper_descriptors that we are intentionally replacing
307
+ else if (!rec->sibling.is_none() && rec->name[0] != '_')
308
+ pybind11_fail("Cannot overload existing non-function object \"" + std::string(rec->name) +
309
+ "\" with a function of the same name");
310
+ }
311
+
312
+ if (!chain) {
313
+ /* No existing overload was found, create a new function object */
314
+ rec->def = new PyMethodDef();
315
+ std::memset(rec->def, 0, sizeof(PyMethodDef));
316
+ rec->def->ml_name = rec->name;
317
+ rec->def->ml_meth = reinterpret_cast<PyCFunction>(reinterpret_cast<void (*) (void)>(*dispatcher));
318
+ rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
319
+
320
+ capsule rec_capsule(rec, [](void *ptr) {
321
+ destruct((detail::function_record *) ptr);
322
+ });
323
+
324
+ object scope_module;
325
+ if (rec->scope) {
326
+ if (hasattr(rec->scope, "__module__")) {
327
+ scope_module = rec->scope.attr("__module__");
328
+ } else if (hasattr(rec->scope, "__name__")) {
329
+ scope_module = rec->scope.attr("__name__");
330
+ }
331
+ }
332
+
333
+ m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.ptr(), scope_module.ptr());
334
+ if (!m_ptr)
335
+ pybind11_fail("cpp_function::cpp_function(): Could not allocate function object");
336
+ } else {
337
+ /* Append at the end of the overload chain */
338
+ m_ptr = rec->sibling.ptr();
339
+ inc_ref();
340
+ chain_start = chain;
341
+ if (chain->is_method != rec->is_method)
342
+ pybind11_fail("overloading a method with both static and instance methods is not supported; "
343
+ #if defined(NDEBUG)
344
+ "compile in debug mode for more details"
345
+ #else
346
+ "error while attempting to bind " + std::string(rec->is_method ? "instance" : "static") + " method " +
347
+ std::string(pybind11::str(rec->scope.attr("__name__"))) + "." + std::string(rec->name) + signature
348
+ #endif
349
+ );
350
+ while (chain->next)
351
+ chain = chain->next;
352
+ chain->next = rec;
353
+ }
354
+
355
+ std::string signatures;
356
+ int index = 0;
357
+ /* Create a nice pydoc rec including all signatures and
358
+ docstrings of the functions in the overload chain */
359
+ if (chain && options::show_function_signatures()) {
360
+ // First a generic signature
361
+ signatures += rec->name;
362
+ signatures += "(*args, **kwargs)\n";
363
+ signatures += "Overloaded function.\n\n";
364
+ }
365
+ // Then specific overload signatures
366
+ bool first_user_def = true;
367
+ for (auto it = chain_start; it != nullptr; it = it->next) {
368
+ if (options::show_function_signatures()) {
369
+ if (index > 0) signatures += "\n";
370
+ if (chain)
371
+ signatures += std::to_string(++index) + ". ";
372
+ signatures += rec->name;
373
+ signatures += it->signature;
374
+ signatures += "\n";
375
+ }
376
+ if (it->doc && strlen(it->doc) > 0 && options::show_user_defined_docstrings()) {
377
+ // If we're appending another docstring, and aren't printing function signatures, we
378
+ // need to append a newline first:
379
+ if (!options::show_function_signatures()) {
380
+ if (first_user_def) first_user_def = false;
381
+ else signatures += "\n";
382
+ }
383
+ if (options::show_function_signatures()) signatures += "\n";
384
+ signatures += it->doc;
385
+ if (options::show_function_signatures()) signatures += "\n";
386
+ }
387
+ }
388
+
389
+ /* Install docstring */
390
+ PyCFunctionObject *func = (PyCFunctionObject *) m_ptr;
391
+ if (func->m_ml->ml_doc)
392
+ std::free(const_cast<char *>(func->m_ml->ml_doc));
393
+ func->m_ml->ml_doc = strdup(signatures.c_str());
394
+
395
+ if (rec->is_method) {
396
+ m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr());
397
+ if (!m_ptr)
398
+ pybind11_fail("cpp_function::cpp_function(): Could not allocate instance method object");
399
+ Py_DECREF(func);
400
+ }
401
+ }
402
+
403
+ /// When a cpp_function is GCed, release any memory allocated by pybind11
404
+ static void destruct(detail::function_record *rec) {
405
+ while (rec) {
406
+ detail::function_record *next = rec->next;
407
+ if (rec->free_data)
408
+ rec->free_data(rec);
409
+ std::free((char *) rec->name);
410
+ std::free((char *) rec->doc);
411
+ std::free((char *) rec->signature);
412
+ for (auto &arg: rec->args) {
413
+ std::free(const_cast<char *>(arg.name));
414
+ std::free(const_cast<char *>(arg.descr));
415
+ arg.value.dec_ref();
416
+ }
417
+ if (rec->def) {
418
+ std::free(const_cast<char *>(rec->def->ml_doc));
419
+ delete rec->def;
420
+ }
421
+ delete rec;
422
+ rec = next;
423
+ }
424
+ }
425
+
426
+ /// Main dispatch logic for calls to functions bound using pybind11
427
+ static PyObject *dispatcher(PyObject *self, PyObject *args_in, PyObject *kwargs_in) {
428
+ using namespace detail;
429
+
430
+ /* Iterator over the list of potentially admissible overloads */
431
+ function_record *overloads = (function_record *) PyCapsule_GetPointer(self, nullptr),
432
+ *it = overloads;
433
+
434
+ /* Need to know how many arguments + keyword arguments there are to pick the right overload */
435
+ const size_t n_args_in = (size_t) PyTuple_GET_SIZE(args_in);
436
+
437
+ handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) : nullptr,
438
+ result = PYBIND11_TRY_NEXT_OVERLOAD;
439
+
440
+ auto self_value_and_holder = value_and_holder();
441
+ if (overloads->is_constructor) {
442
+ const auto tinfo = get_type_info((PyTypeObject *) overloads->scope.ptr());
443
+ const auto pi = reinterpret_cast<instance *>(parent.ptr());
444
+ self_value_and_holder = pi->get_value_and_holder(tinfo, false);
445
+
446
+ if (!self_value_and_holder.type || !self_value_and_holder.inst) {
447
+ PyErr_SetString(PyExc_TypeError, "__init__(self, ...) called with invalid `self` argument");
448
+ return nullptr;
449
+ }
450
+
451
+ // If this value is already registered it must mean __init__ is invoked multiple times;
452
+ // we really can't support that in C++, so just ignore the second __init__.
453
+ if (self_value_and_holder.instance_registered())
454
+ return none().release().ptr();
455
+ }
456
+
457
+ try {
458
+ // We do this in two passes: in the first pass, we load arguments with `convert=false`;
459
+ // in the second, we allow conversion (except for arguments with an explicit
460
+ // py::arg().noconvert()). This lets us prefer calls without conversion, with
461
+ // conversion as a fallback.
462
+ std::vector<function_call> second_pass;
463
+
464
+ // However, if there are no overloads, we can just skip the no-convert pass entirely
465
+ const bool overloaded = it != nullptr && it->next != nullptr;
466
+
467
+ for (; it != nullptr; it = it->next) {
468
+
469
+ /* For each overload:
470
+ 1. Copy all positional arguments we were given, also checking to make sure that
471
+ named positional arguments weren't *also* specified via kwarg.
472
+ 2. If we weren't given enough, try to make up the omitted ones by checking
473
+ whether they were provided by a kwarg matching the `py::arg("name")` name. If
474
+ so, use it (and remove it from kwargs; if not, see if the function binding
475
+ provided a default that we can use.
476
+ 3. Ensure that either all keyword arguments were "consumed", or that the function
477
+ takes a kwargs argument to accept unconsumed kwargs.
478
+ 4. Any positional arguments still left get put into a tuple (for args), and any
479
+ leftover kwargs get put into a dict.
480
+ 5. Pack everything into a vector; if we have py::args or py::kwargs, they are an
481
+ extra tuple or dict at the end of the positional arguments.
482
+ 6. Call the function call dispatcher (function_record::impl)
483
+
484
+ If one of these fail, move on to the next overload and keep trying until we get a
485
+ result other than PYBIND11_TRY_NEXT_OVERLOAD.
486
+ */
487
+
488
+ function_record &func = *it;
489
+ size_t pos_args = func.nargs; // Number of positional arguments that we need
490
+ if (func.has_args) --pos_args; // (but don't count py::args
491
+ if (func.has_kwargs) --pos_args; // or py::kwargs)
492
+
493
+ if (!func.has_args && n_args_in > pos_args)
494
+ continue; // Too many arguments for this overload
495
+
496
+ if (n_args_in < pos_args && func.args.size() < pos_args)
497
+ continue; // Not enough arguments given, and not enough defaults to fill in the blanks
498
+
499
+ function_call call(func, parent);
500
+
501
+ size_t args_to_copy = std::min(pos_args, n_args_in);
502
+ size_t args_copied = 0;
503
+
504
+ // 0. Inject new-style `self` argument
505
+ if (func.is_new_style_constructor) {
506
+ // The `value` may have been preallocated by an old-style `__init__`
507
+ // if it was a preceding candidate for overload resolution.
508
+ if (self_value_and_holder)
509
+ self_value_and_holder.type->dealloc(self_value_and_holder);
510
+
511
+ call.init_self = PyTuple_GET_ITEM(args_in, 0);
512
+ call.args.push_back(reinterpret_cast<PyObject *>(&self_value_and_holder));
513
+ call.args_convert.push_back(false);
514
+ ++args_copied;
515
+ }
516
+
517
+ // 1. Copy any position arguments given.
518
+ bool bad_arg = false;
519
+ for (; args_copied < args_to_copy; ++args_copied) {
520
+ argument_record *arg_rec = args_copied < func.args.size() ? &func.args[args_copied] : nullptr;
521
+ if (kwargs_in && arg_rec && arg_rec->name && PyDict_GetItemString(kwargs_in, arg_rec->name)) {
522
+ bad_arg = true;
523
+ break;
524
+ }
525
+
526
+ handle arg(PyTuple_GET_ITEM(args_in, args_copied));
527
+ if (arg_rec && !arg_rec->none && arg.is_none()) {
528
+ bad_arg = true;
529
+ break;
530
+ }
531
+ call.args.push_back(arg);
532
+ call.args_convert.push_back(arg_rec ? arg_rec->convert : true);
533
+ }
534
+ if (bad_arg)
535
+ continue; // Maybe it was meant for another overload (issue #688)
536
+
537
+ // We'll need to copy this if we steal some kwargs for defaults
538
+ dict kwargs = reinterpret_borrow<dict>(kwargs_in);
539
+
540
+ // 2. Check kwargs and, failing that, defaults that may help complete the list
541
+ if (args_copied < pos_args) {
542
+ bool copied_kwargs = false;
543
+
544
+ for (; args_copied < pos_args; ++args_copied) {
545
+ const auto &arg = func.args[args_copied];
546
+
547
+ handle value;
548
+ if (kwargs_in && arg.name)
549
+ value = PyDict_GetItemString(kwargs.ptr(), arg.name);
550
+
551
+ if (value) {
552
+ // Consume a kwargs value
553
+ if (!copied_kwargs) {
554
+ kwargs = reinterpret_steal<dict>(PyDict_Copy(kwargs.ptr()));
555
+ copied_kwargs = true;
556
+ }
557
+ PyDict_DelItemString(kwargs.ptr(), arg.name);
558
+ } else if (arg.value) {
559
+ value = arg.value;
560
+ }
561
+
562
+ if (value) {
563
+ call.args.push_back(value);
564
+ call.args_convert.push_back(arg.convert);
565
+ }
566
+ else
567
+ break;
568
+ }
569
+
570
+ if (args_copied < pos_args)
571
+ continue; // Not enough arguments, defaults, or kwargs to fill the positional arguments
572
+ }
573
+
574
+ // 3. Check everything was consumed (unless we have a kwargs arg)
575
+ if (kwargs && kwargs.size() > 0 && !func.has_kwargs)
576
+ continue; // Unconsumed kwargs, but no py::kwargs argument to accept them
577
+
578
+ // 4a. If we have a py::args argument, create a new tuple with leftovers
579
+ if (func.has_args) {
580
+ tuple extra_args;
581
+ if (args_to_copy == 0) {
582
+ // We didn't copy out any position arguments from the args_in tuple, so we
583
+ // can reuse it directly without copying:
584
+ extra_args = reinterpret_borrow<tuple>(args_in);
585
+ } else if (args_copied >= n_args_in) {
586
+ extra_args = tuple(0);
587
+ } else {
588
+ size_t args_size = n_args_in - args_copied;
589
+ extra_args = tuple(args_size);
590
+ for (size_t i = 0; i < args_size; ++i) {
591
+ extra_args[i] = PyTuple_GET_ITEM(args_in, args_copied + i);
592
+ }
593
+ }
594
+ call.args.push_back(extra_args);
595
+ call.args_convert.push_back(false);
596
+ call.args_ref = std::move(extra_args);
597
+ }
598
+
599
+ // 4b. If we have a py::kwargs, pass on any remaining kwargs
600
+ if (func.has_kwargs) {
601
+ if (!kwargs.ptr())
602
+ kwargs = dict(); // If we didn't get one, send an empty one
603
+ call.args.push_back(kwargs);
604
+ call.args_convert.push_back(false);
605
+ call.kwargs_ref = std::move(kwargs);
606
+ }
607
+
608
+ // 5. Put everything in a vector. Not technically step 5, we've been building it
609
+ // in `call.args` all along.
610
+ #if !defined(NDEBUG)
611
+ if (call.args.size() != func.nargs || call.args_convert.size() != func.nargs)
612
+ pybind11_fail("Internal error: function call dispatcher inserted wrong number of arguments!");
613
+ #endif
614
+
615
+ std::vector<bool> second_pass_convert;
616
+ if (overloaded) {
617
+ // We're in the first no-convert pass, so swap out the conversion flags for a
618
+ // set of all-false flags. If the call fails, we'll swap the flags back in for
619
+ // the conversion-allowed call below.
620
+ second_pass_convert.resize(func.nargs, false);
621
+ call.args_convert.swap(second_pass_convert);
622
+ }
623
+
624
+ // 6. Call the function.
625
+ try {
626
+ loader_life_support guard{};
627
+ result = func.impl(call);
628
+ } catch (reference_cast_error &) {
629
+ result = PYBIND11_TRY_NEXT_OVERLOAD;
630
+ }
631
+
632
+ if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD)
633
+ break;
634
+
635
+ if (overloaded) {
636
+ // The (overloaded) call failed; if the call has at least one argument that
637
+ // permits conversion (i.e. it hasn't been explicitly specified `.noconvert()`)
638
+ // then add this call to the list of second pass overloads to try.
639
+ for (size_t i = func.is_method ? 1 : 0; i < pos_args; i++) {
640
+ if (second_pass_convert[i]) {
641
+ // Found one: swap the converting flags back in and store the call for
642
+ // the second pass.
643
+ call.args_convert.swap(second_pass_convert);
644
+ second_pass.push_back(std::move(call));
645
+ break;
646
+ }
647
+ }
648
+ }
649
+ }
650
+
651
+ if (overloaded && !second_pass.empty() && result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
652
+ // The no-conversion pass finished without success, try again with conversion allowed
653
+ for (auto &call : second_pass) {
654
+ try {
655
+ loader_life_support guard{};
656
+ result = call.func.impl(call);
657
+ } catch (reference_cast_error &) {
658
+ result = PYBIND11_TRY_NEXT_OVERLOAD;
659
+ }
660
+
661
+ if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD)
662
+ break;
663
+ }
664
+ }
665
+ } catch (error_already_set &e) {
666
+ e.restore();
667
+ return nullptr;
668
+ } catch (...) {
669
+ /* When an exception is caught, give each registered exception
670
+ translator a chance to translate it to a Python exception
671
+ in reverse order of registration.
672
+
673
+ A translator may choose to do one of the following:
674
+
675
+ - catch the exception and call PyErr_SetString or PyErr_SetObject
676
+ to set a standard (or custom) Python exception, or
677
+ - do nothing and let the exception fall through to the next translator, or
678
+ - delegate translation to the next translator by throwing a new type of exception. */
679
+
680
+ auto last_exception = std::current_exception();
681
+ auto &registered_exception_translators = get_internals().registered_exception_translators;
682
+ for (auto& translator : registered_exception_translators) {
683
+ try {
684
+ translator(last_exception);
685
+ } catch (...) {
686
+ last_exception = std::current_exception();
687
+ continue;
688
+ }
689
+ return nullptr;
690
+ }
691
+ PyErr_SetString(PyExc_SystemError, "Exception escaped from default exception translator!");
692
+ return nullptr;
693
+ }
694
+
695
+ auto append_note_if_missing_header_is_suspected = [](std::string &msg) {
696
+ if (msg.find("std::") != std::string::npos) {
697
+ msg += "\n\n"
698
+ "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
699
+ "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
700
+ "conversions are optional and require extra headers to be included\n"
701
+ "when compiling your pybind11 module.";
702
+ }
703
+ };
704
+
705
+ if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
706
+ if (overloads->is_operator)
707
+ return handle(Py_NotImplemented).inc_ref().ptr();
708
+
709
+ std::string msg = std::string(overloads->name) + "(): incompatible " +
710
+ std::string(overloads->is_constructor ? "constructor" : "function") +
711
+ " arguments. The following argument types are supported:\n";
712
+
713
+ int ctr = 0;
714
+ for (function_record *it2 = overloads; it2 != nullptr; it2 = it2->next) {
715
+ msg += " "+ std::to_string(++ctr) + ". ";
716
+
717
+ bool wrote_sig = false;
718
+ if (overloads->is_constructor) {
719
+ // For a constructor, rewrite `(self: Object, arg0, ...) -> NoneType` as `Object(arg0, ...)`
720
+ std::string sig = it2->signature;
721
+ size_t start = sig.find('(') + 7; // skip "(self: "
722
+ if (start < sig.size()) {
723
+ // End at the , for the next argument
724
+ size_t end = sig.find(", "), next = end + 2;
725
+ size_t ret = sig.rfind(" -> ");
726
+ // Or the ), if there is no comma:
727
+ if (end >= sig.size()) next = end = sig.find(')');
728
+ if (start < end && next < sig.size()) {
729
+ msg.append(sig, start, end - start);
730
+ msg += '(';
731
+ msg.append(sig, next, ret - next);
732
+ wrote_sig = true;
733
+ }
734
+ }
735
+ }
736
+ if (!wrote_sig) msg += it2->signature;
737
+
738
+ msg += "\n";
739
+ }
740
+ msg += "\nInvoked with: ";
741
+ auto args_ = reinterpret_borrow<tuple>(args_in);
742
+ bool some_args = false;
743
+ for (size_t ti = overloads->is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
744
+ if (!some_args) some_args = true;
745
+ else msg += ", ";
746
+ msg += pybind11::repr(args_[ti]);
747
+ }
748
+ if (kwargs_in) {
749
+ auto kwargs = reinterpret_borrow<dict>(kwargs_in);
750
+ if (kwargs.size() > 0) {
751
+ if (some_args) msg += "; ";
752
+ msg += "kwargs: ";
753
+ bool first = true;
754
+ for (auto kwarg : kwargs) {
755
+ if (first) first = false;
756
+ else msg += ", ";
757
+ msg += pybind11::str("{}={!r}").format(kwarg.first, kwarg.second);
758
+ }
759
+ }
760
+ }
761
+
762
+ append_note_if_missing_header_is_suspected(msg);
763
+ PyErr_SetString(PyExc_TypeError, msg.c_str());
764
+ return nullptr;
765
+ } else if (!result) {
766
+ std::string msg = "Unable to convert function return value to a "
767
+ "Python type! The signature was\n\t";
768
+ msg += it->signature;
769
+ append_note_if_missing_header_is_suspected(msg);
770
+ PyErr_SetString(PyExc_TypeError, msg.c_str());
771
+ return nullptr;
772
+ } else {
773
+ if (overloads->is_constructor && !self_value_and_holder.holder_constructed()) {
774
+ auto *pi = reinterpret_cast<instance *>(parent.ptr());
775
+ self_value_and_holder.type->init_instance(pi, nullptr);
776
+ }
777
+ return result.ptr();
778
+ }
779
+ }
780
+ };
781
+
782
+ /// Wrapper for Python extension modules
783
+ class module : public object {
784
+ public:
785
+ PYBIND11_OBJECT_DEFAULT(module, object, PyModule_Check)
786
+
787
+ /// Create a new top-level Python module with the given name and docstring
788
+ explicit module(const char *name, const char *doc = nullptr) {
789
+ if (!options::show_user_defined_docstrings()) doc = nullptr;
790
+ #if PY_MAJOR_VERSION >= 3
791
+ PyModuleDef *def = new PyModuleDef();
792
+ std::memset(def, 0, sizeof(PyModuleDef));
793
+ def->m_name = name;
794
+ def->m_doc = doc;
795
+ def->m_size = -1;
796
+ Py_INCREF(def);
797
+ m_ptr = PyModule_Create(def);
798
+ #else
799
+ m_ptr = Py_InitModule3(name, nullptr, doc);
800
+ #endif
801
+ if (m_ptr == nullptr)
802
+ pybind11_fail("Internal error in module::module()");
803
+ inc_ref();
804
+ }
805
+
806
+ /** \rst
807
+ Create Python binding for a new function within the module scope. ``Func``
808
+ can be a plain C++ function, a function pointer, or a lambda function. For
809
+ details on the ``Extra&& ... extra`` argument, see section :ref:`extras`.
810
+ \endrst */
811
+ template <typename Func, typename... Extra>
812
+ module &def(const char *name_, Func &&f, const Extra& ... extra) {
813
+ cpp_function func(std::forward<Func>(f), name(name_), scope(*this),
814
+ sibling(getattr(*this, name_, none())), extra...);
815
+ // NB: allow overwriting here because cpp_function sets up a chain with the intention of
816
+ // overwriting (and has already checked internally that it isn't overwriting non-functions).
817
+ add_object(name_, func, true /* overwrite */);
818
+ return *this;
819
+ }
820
+
821
+ /** \rst
822
+ Create and return a new Python submodule with the given name and docstring.
823
+ This also works recursively, i.e.
824
+
825
+ .. code-block:: cpp
826
+
827
+ py::module m("example", "pybind11 example plugin");
828
+ py::module m2 = m.def_submodule("sub", "A submodule of 'example'");
829
+ py::module m3 = m2.def_submodule("subsub", "A submodule of 'example.sub'");
830
+ \endrst */
831
+ module def_submodule(const char *name, const char *doc = nullptr) {
832
+ std::string full_name = std::string(PyModule_GetName(m_ptr))
833
+ + std::string(".") + std::string(name);
834
+ auto result = reinterpret_borrow<module>(PyImport_AddModule(full_name.c_str()));
835
+ if (doc && options::show_user_defined_docstrings())
836
+ result.attr("__doc__") = pybind11::str(doc);
837
+ attr(name) = result;
838
+ return result;
839
+ }
840
+
841
+ /// Import and return a module or throws `error_already_set`.
842
+ static module import(const char *name) {
843
+ PyObject *obj = PyImport_ImportModule(name);
844
+ if (!obj)
845
+ throw error_already_set();
846
+ return reinterpret_steal<module>(obj);
847
+ }
848
+
849
+ /// Reload the module or throws `error_already_set`.
850
+ void reload() {
851
+ PyObject *obj = PyImport_ReloadModule(ptr());
852
+ if (!obj)
853
+ throw error_already_set();
854
+ *this = reinterpret_steal<module>(obj);
855
+ }
856
+
857
+ // Adds an object to the module using the given name. Throws if an object with the given name
858
+ // already exists.
859
+ //
860
+ // overwrite should almost always be false: attempting to overwrite objects that pybind11 has
861
+ // established will, in most cases, break things.
862
+ PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite = false) {
863
+ if (!overwrite && hasattr(*this, name))
864
+ pybind11_fail("Error during initialization: multiple incompatible definitions with name \"" +
865
+ std::string(name) + "\"");
866
+
867
+ PyModule_AddObject(ptr(), name, obj.inc_ref().ptr() /* steals a reference */);
868
+ }
869
+ };
870
+
871
+ /// \ingroup python_builtins
872
+ /// Return a dictionary representing the global variables in the current execution frame,
873
+ /// or ``__main__.__dict__`` if there is no frame (usually when the interpreter is embedded).
874
+ inline dict globals() {
875
+ PyObject *p = PyEval_GetGlobals();
876
+ return reinterpret_borrow<dict>(p ? p : module::import("__main__").attr("__dict__").ptr());
877
+ }
878
+
879
+ NAMESPACE_BEGIN(detail)
880
+ /// Generic support for creating new Python heap types
881
+ class generic_type : public object {
882
+ template <typename...> friend class class_;
883
+ public:
884
+ PYBIND11_OBJECT_DEFAULT(generic_type, object, PyType_Check)
885
+ protected:
886
+ void initialize(const type_record &rec) {
887
+ if (rec.scope && hasattr(rec.scope, rec.name))
888
+ pybind11_fail("generic_type: cannot initialize type \"" + std::string(rec.name) +
889
+ "\": an object with that name is already defined");
890
+
891
+ if (rec.module_local ? get_local_type_info(*rec.type) : get_global_type_info(*rec.type))
892
+ pybind11_fail("generic_type: type \"" + std::string(rec.name) +
893
+ "\" is already registered!");
894
+
895
+ m_ptr = make_new_python_type(rec);
896
+
897
+ /* Register supplemental type information in C++ dict */
898
+ auto *tinfo = new detail::type_info();
899
+ tinfo->type = (PyTypeObject *) m_ptr;
900
+ tinfo->cpptype = rec.type;
901
+ tinfo->type_size = rec.type_size;
902
+ tinfo->operator_new = rec.operator_new;
903
+ tinfo->holder_size_in_ptrs = size_in_ptrs(rec.holder_size);
904
+ tinfo->init_instance = rec.init_instance;
905
+ tinfo->dealloc = rec.dealloc;
906
+ tinfo->simple_type = true;
907
+ tinfo->simple_ancestors = true;
908
+ tinfo->default_holder = rec.default_holder;
909
+ tinfo->module_local = rec.module_local;
910
+
911
+ auto &internals = get_internals();
912
+ auto tindex = std::type_index(*rec.type);
913
+ tinfo->direct_conversions = &internals.direct_conversions[tindex];
914
+ if (rec.module_local)
915
+ registered_local_types_cpp()[tindex] = tinfo;
916
+ else
917
+ internals.registered_types_cpp[tindex] = tinfo;
918
+ internals.registered_types_py[(PyTypeObject *) m_ptr] = { tinfo };
919
+
920
+ if (rec.bases.size() > 1 || rec.multiple_inheritance) {
921
+ mark_parents_nonsimple(tinfo->type);
922
+ tinfo->simple_ancestors = false;
923
+ }
924
+ else if (rec.bases.size() == 1) {
925
+ auto parent_tinfo = get_type_info((PyTypeObject *) rec.bases[0].ptr());
926
+ tinfo->simple_ancestors = parent_tinfo->simple_ancestors;
927
+ }
928
+
929
+ if (rec.module_local) {
930
+ // Stash the local typeinfo and loader so that external modules can access it.
931
+ tinfo->module_local_load = &type_caster_generic::local_load;
932
+ setattr(m_ptr, PYBIND11_MODULE_LOCAL_ID, capsule(tinfo));
933
+ }
934
+ }
935
+
936
+ /// Helper function which tags all parents of a type using mult. inheritance
937
+ void mark_parents_nonsimple(PyTypeObject *value) {
938
+ auto t = reinterpret_borrow<tuple>(value->tp_bases);
939
+ for (handle h : t) {
940
+ auto tinfo2 = get_type_info((PyTypeObject *) h.ptr());
941
+ if (tinfo2)
942
+ tinfo2->simple_type = false;
943
+ mark_parents_nonsimple((PyTypeObject *) h.ptr());
944
+ }
945
+ }
946
+
947
+ void install_buffer_funcs(
948
+ buffer_info *(*get_buffer)(PyObject *, void *),
949
+ void *get_buffer_data) {
950
+ PyHeapTypeObject *type = (PyHeapTypeObject*) m_ptr;
951
+ auto tinfo = detail::get_type_info(&type->ht_type);
952
+
953
+ if (!type->ht_type.tp_as_buffer)
954
+ pybind11_fail(
955
+ "To be able to register buffer protocol support for the type '" +
956
+ std::string(tinfo->type->tp_name) +
957
+ "' the associated class<>(..) invocation must "
958
+ "include the pybind11::buffer_protocol() annotation!");
959
+
960
+ tinfo->get_buffer = get_buffer;
961
+ tinfo->get_buffer_data = get_buffer_data;
962
+ }
963
+
964
+ void def_property_static_impl(const char *name,
965
+ handle fget, handle fset,
966
+ detail::function_record *rec_fget) {
967
+ const auto is_static = !(rec_fget->is_method && rec_fget->scope);
968
+ const auto has_doc = rec_fget->doc && pybind11::options::show_user_defined_docstrings();
969
+
970
+ auto property = handle((PyObject *) (is_static ? get_internals().static_property_type
971
+ : &PyProperty_Type));
972
+ attr(name) = property(fget.ptr() ? fget : none(),
973
+ fset.ptr() ? fset : none(),
974
+ /*deleter*/none(),
975
+ pybind11::str(has_doc ? rec_fget->doc : ""));
976
+ }
977
+ };
978
+
979
+ /// Set the pointer to operator new if it exists. The cast is needed because it can be overloaded.
980
+ template <typename T, typename = void_t<decltype(static_cast<void *(*)(size_t)>(T::operator new))>>
981
+ void set_operator_new(type_record *r) { r->operator_new = &T::operator new; }
982
+
983
+ template <typename> void set_operator_new(...) { }
984
+
985
+ template <typename T, typename SFINAE = void> struct has_operator_delete : std::false_type { };
986
+ template <typename T> struct has_operator_delete<T, void_t<decltype(static_cast<void (*)(void *)>(T::operator delete))>>
987
+ : std::true_type { };
988
+ template <typename T, typename SFINAE = void> struct has_operator_delete_size : std::false_type { };
989
+ template <typename T> struct has_operator_delete_size<T, void_t<decltype(static_cast<void (*)(void *, size_t)>(T::operator delete))>>
990
+ : std::true_type { };
991
+ /// Call class-specific delete if it exists or global otherwise. Can also be an overload set.
992
+ template <typename T, enable_if_t<has_operator_delete<T>::value, int> = 0>
993
+ void call_operator_delete(T *p, size_t) { T::operator delete(p); }
994
+ template <typename T, enable_if_t<!has_operator_delete<T>::value && has_operator_delete_size<T>::value, int> = 0>
995
+ void call_operator_delete(T *p, size_t s) { T::operator delete(p, s); }
996
+
997
+ inline void call_operator_delete(void *p, size_t) { ::operator delete(p); }
998
+
999
+ NAMESPACE_END(detail)
1000
+
1001
+ /// Given a pointer to a member function, cast it to its `Derived` version.
1002
+ /// Forward everything else unchanged.
1003
+ template <typename /*Derived*/, typename F>
1004
+ auto method_adaptor(F &&f) -> decltype(std::forward<F>(f)) { return std::forward<F>(f); }
1005
+
1006
+ template <typename Derived, typename Return, typename Class, typename... Args>
1007
+ auto method_adaptor(Return (Class::*pmf)(Args...)) -> Return (Derived::*)(Args...) { return pmf; }
1008
+
1009
+ template <typename Derived, typename Return, typename Class, typename... Args>
1010
+ auto method_adaptor(Return (Class::*pmf)(Args...) const) -> Return (Derived::*)(Args...) const { return pmf; }
1011
+
1012
+ template <typename type_, typename... options>
1013
+ class class_ : public detail::generic_type {
1014
+ template <typename T> using is_holder = detail::is_holder_type<type_, T>;
1015
+ template <typename T> using is_subtype = detail::is_strict_base_of<type_, T>;
1016
+ template <typename T> using is_base = detail::is_strict_base_of<T, type_>;
1017
+ // struct instead of using here to help MSVC:
1018
+ template <typename T> struct is_valid_class_option :
1019
+ detail::any_of<is_holder<T>, is_subtype<T>, is_base<T>> {};
1020
+
1021
+ public:
1022
+ using type = type_;
1023
+ using type_alias = detail::exactly_one_t<is_subtype, void, options...>;
1024
+ constexpr static bool has_alias = !std::is_void<type_alias>::value;
1025
+ using holder_type = detail::exactly_one_t<is_holder, std::unique_ptr<type>, options...>;
1026
+
1027
+ static_assert(detail::all_of<is_valid_class_option<options>...>::value,
1028
+ "Unknown/invalid class_ template parameters provided");
1029
+
1030
+ static_assert(!has_alias || std::is_polymorphic<type>::value,
1031
+ "Cannot use an alias class with a non-polymorphic type");
1032
+
1033
+ PYBIND11_OBJECT(class_, generic_type, PyType_Check)
1034
+
1035
+ template <typename... Extra>
1036
+ class_(handle scope, const char *name, const Extra &... extra) {
1037
+ using namespace detail;
1038
+
1039
+ // MI can only be specified via class_ template options, not constructor parameters
1040
+ static_assert(
1041
+ none_of<is_pyobject<Extra>...>::value || // no base class arguments, or:
1042
+ ( constexpr_sum(is_pyobject<Extra>::value...) == 1 && // Exactly one base
1043
+ constexpr_sum(is_base<options>::value...) == 0 && // no template option bases
1044
+ none_of<std::is_same<multiple_inheritance, Extra>...>::value), // no multiple_inheritance attr
1045
+ "Error: multiple inheritance bases must be specified via class_ template options");
1046
+
1047
+ type_record record;
1048
+ record.scope = scope;
1049
+ record.name = name;
1050
+ record.type = &typeid(type);
1051
+ record.type_size = sizeof(conditional_t<has_alias, type_alias, type>);
1052
+ record.holder_size = sizeof(holder_type);
1053
+ record.init_instance = init_instance;
1054
+ record.dealloc = dealloc;
1055
+ record.default_holder = std::is_same<holder_type, std::unique_ptr<type>>::value;
1056
+
1057
+ set_operator_new<type>(&record);
1058
+
1059
+ /* Register base classes specified via template arguments to class_, if any */
1060
+ PYBIND11_EXPAND_SIDE_EFFECTS(add_base<options>(record));
1061
+
1062
+ /* Process optional arguments, if any */
1063
+ process_attributes<Extra...>::init(extra..., &record);
1064
+
1065
+ generic_type::initialize(record);
1066
+
1067
+ if (has_alias) {
1068
+ auto &instances = record.module_local ? registered_local_types_cpp() : get_internals().registered_types_cpp;
1069
+ instances[std::type_index(typeid(type_alias))] = instances[std::type_index(typeid(type))];
1070
+ }
1071
+ }
1072
+
1073
+ template <typename Base, detail::enable_if_t<is_base<Base>::value, int> = 0>
1074
+ static void add_base(detail::type_record &rec) {
1075
+ rec.add_base(typeid(Base), [](void *src) -> void * {
1076
+ return static_cast<Base *>(reinterpret_cast<type *>(src));
1077
+ });
1078
+ }
1079
+
1080
+ template <typename Base, detail::enable_if_t<!is_base<Base>::value, int> = 0>
1081
+ static void add_base(detail::type_record &) { }
1082
+
1083
+ template <typename Func, typename... Extra>
1084
+ class_ &def(const char *name_, Func&& f, const Extra&... extra) {
1085
+ cpp_function cf(method_adaptor<type>(std::forward<Func>(f)), name(name_), is_method(*this),
1086
+ sibling(getattr(*this, name_, none())), extra...);
1087
+ attr(cf.name()) = cf;
1088
+ return *this;
1089
+ }
1090
+
1091
+ template <typename Func, typename... Extra> class_ &
1092
+ def_static(const char *name_, Func &&f, const Extra&... extra) {
1093
+ static_assert(!std::is_member_function_pointer<Func>::value,
1094
+ "def_static(...) called with a non-static member function pointer");
1095
+ cpp_function cf(std::forward<Func>(f), name(name_), scope(*this),
1096
+ sibling(getattr(*this, name_, none())), extra...);
1097
+ attr(cf.name()) = cf;
1098
+ return *this;
1099
+ }
1100
+
1101
+ template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
1102
+ class_ &def(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
1103
+ op.execute(*this, extra...);
1104
+ return *this;
1105
+ }
1106
+
1107
+ template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
1108
+ class_ & def_cast(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
1109
+ op.execute_cast(*this, extra...);
1110
+ return *this;
1111
+ }
1112
+
1113
+ template <typename... Args, typename... Extra>
1114
+ class_ &def(const detail::initimpl::constructor<Args...> &init, const Extra&... extra) {
1115
+ init.execute(*this, extra...);
1116
+ return *this;
1117
+ }
1118
+
1119
+ template <typename... Args, typename... Extra>
1120
+ class_ &def(const detail::initimpl::alias_constructor<Args...> &init, const Extra&... extra) {
1121
+ init.execute(*this, extra...);
1122
+ return *this;
1123
+ }
1124
+
1125
+ template <typename... Args, typename... Extra>
1126
+ class_ &def(detail::initimpl::factory<Args...> &&init, const Extra&... extra) {
1127
+ std::move(init).execute(*this, extra...);
1128
+ return *this;
1129
+ }
1130
+
1131
+ template <typename... Args, typename... Extra>
1132
+ class_ &def(detail::initimpl::pickle_factory<Args...> &&pf, const Extra &...extra) {
1133
+ std::move(pf).execute(*this, extra...);
1134
+ return *this;
1135
+ }
1136
+
1137
+ template <typename Func> class_& def_buffer(Func &&func) {
1138
+ struct capture { Func func; };
1139
+ capture *ptr = new capture { std::forward<Func>(func) };
1140
+ install_buffer_funcs([](PyObject *obj, void *ptr) -> buffer_info* {
1141
+ detail::make_caster<type> caster;
1142
+ if (!caster.load(obj, false))
1143
+ return nullptr;
1144
+ return new buffer_info(((capture *) ptr)->func(caster));
1145
+ }, ptr);
1146
+ return *this;
1147
+ }
1148
+
1149
+ template <typename Return, typename Class, typename... Args>
1150
+ class_ &def_buffer(Return (Class::*func)(Args...)) {
1151
+ return def_buffer([func] (type &obj) { return (obj.*func)(); });
1152
+ }
1153
+
1154
+ template <typename Return, typename Class, typename... Args>
1155
+ class_ &def_buffer(Return (Class::*func)(Args...) const) {
1156
+ return def_buffer([func] (const type &obj) { return (obj.*func)(); });
1157
+ }
1158
+
1159
+ template <typename C, typename D, typename... Extra>
1160
+ class_ &def_readwrite(const char *name, D C::*pm, const Extra&... extra) {
1161
+ static_assert(std::is_base_of<C, type>::value, "def_readwrite() requires a class member (or base class member)");
1162
+ cpp_function fget([pm](const type &c) -> const D &{ return c.*pm; }, is_method(*this)),
1163
+ fset([pm](type &c, const D &value) { c.*pm = value; }, is_method(*this));
1164
+ def_property(name, fget, fset, return_value_policy::reference_internal, extra...);
1165
+ return *this;
1166
+ }
1167
+
1168
+ template <typename C, typename D, typename... Extra>
1169
+ class_ &def_readonly(const char *name, const D C::*pm, const Extra& ...extra) {
1170
+ static_assert(std::is_base_of<C, type>::value, "def_readonly() requires a class member (or base class member)");
1171
+ cpp_function fget([pm](const type &c) -> const D &{ return c.*pm; }, is_method(*this));
1172
+ def_property_readonly(name, fget, return_value_policy::reference_internal, extra...);
1173
+ return *this;
1174
+ }
1175
+
1176
+ template <typename D, typename... Extra>
1177
+ class_ &def_readwrite_static(const char *name, D *pm, const Extra& ...extra) {
1178
+ cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this)),
1179
+ fset([pm](object, const D &value) { *pm = value; }, scope(*this));
1180
+ def_property_static(name, fget, fset, return_value_policy::reference, extra...);
1181
+ return *this;
1182
+ }
1183
+
1184
+ template <typename D, typename... Extra>
1185
+ class_ &def_readonly_static(const char *name, const D *pm, const Extra& ...extra) {
1186
+ cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this));
1187
+ def_property_readonly_static(name, fget, return_value_policy::reference, extra...);
1188
+ return *this;
1189
+ }
1190
+
1191
+ /// Uses return_value_policy::reference_internal by default
1192
+ template <typename Getter, typename... Extra>
1193
+ class_ &def_property_readonly(const char *name, const Getter &fget, const Extra& ...extra) {
1194
+ return def_property_readonly(name, cpp_function(method_adaptor<type>(fget)),
1195
+ return_value_policy::reference_internal, extra...);
1196
+ }
1197
+
1198
+ /// Uses cpp_function's return_value_policy by default
1199
+ template <typename... Extra>
1200
+ class_ &def_property_readonly(const char *name, const cpp_function &fget, const Extra& ...extra) {
1201
+ return def_property(name, fget, cpp_function(), extra...);
1202
+ }
1203
+
1204
+ /// Uses return_value_policy::reference by default
1205
+ template <typename Getter, typename... Extra>
1206
+ class_ &def_property_readonly_static(const char *name, const Getter &fget, const Extra& ...extra) {
1207
+ return def_property_readonly_static(name, cpp_function(fget), return_value_policy::reference, extra...);
1208
+ }
1209
+
1210
+ /// Uses cpp_function's return_value_policy by default
1211
+ template <typename... Extra>
1212
+ class_ &def_property_readonly_static(const char *name, const cpp_function &fget, const Extra& ...extra) {
1213
+ return def_property_static(name, fget, cpp_function(), extra...);
1214
+ }
1215
+
1216
+ /// Uses return_value_policy::reference_internal by default
1217
+ template <typename Getter, typename Setter, typename... Extra>
1218
+ class_ &def_property(const char *name, const Getter &fget, const Setter &fset, const Extra& ...extra) {
1219
+ return def_property(name, fget, cpp_function(method_adaptor<type>(fset)), extra...);
1220
+ }
1221
+ template <typename Getter, typename... Extra>
1222
+ class_ &def_property(const char *name, const Getter &fget, const cpp_function &fset, const Extra& ...extra) {
1223
+ return def_property(name, cpp_function(method_adaptor<type>(fget)), fset,
1224
+ return_value_policy::reference_internal, extra...);
1225
+ }
1226
+
1227
+ /// Uses cpp_function's return_value_policy by default
1228
+ template <typename... Extra>
1229
+ class_ &def_property(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
1230
+ return def_property_static(name, fget, fset, is_method(*this), extra...);
1231
+ }
1232
+
1233
+ /// Uses return_value_policy::reference by default
1234
+ template <typename Getter, typename... Extra>
1235
+ class_ &def_property_static(const char *name, const Getter &fget, const cpp_function &fset, const Extra& ...extra) {
1236
+ return def_property_static(name, cpp_function(fget), fset, return_value_policy::reference, extra...);
1237
+ }
1238
+
1239
+ /// Uses cpp_function's return_value_policy by default
1240
+ template <typename... Extra>
1241
+ class_ &def_property_static(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
1242
+ auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
1243
+ char *doc_prev = rec_fget->doc; /* 'extra' field may include a property-specific documentation string */
1244
+ detail::process_attributes<Extra...>::init(extra..., rec_fget);
1245
+ if (rec_fget->doc && rec_fget->doc != doc_prev) {
1246
+ free(doc_prev);
1247
+ rec_fget->doc = strdup(rec_fget->doc);
1248
+ }
1249
+ if (rec_fset) {
1250
+ doc_prev = rec_fset->doc;
1251
+ detail::process_attributes<Extra...>::init(extra..., rec_fset);
1252
+ if (rec_fset->doc && rec_fset->doc != doc_prev) {
1253
+ free(doc_prev);
1254
+ rec_fset->doc = strdup(rec_fset->doc);
1255
+ }
1256
+ }
1257
+ def_property_static_impl(name, fget, fset, rec_fget);
1258
+ return *this;
1259
+ }
1260
+
1261
+ private:
1262
+ /// Initialize holder object, variant 1: object derives from enable_shared_from_this
1263
+ template <typename T>
1264
+ static void init_holder(detail::instance *inst, detail::value_and_holder &v_h,
1265
+ const holder_type * /* unused */, const std::enable_shared_from_this<T> * /* dummy */) {
1266
+ try {
1267
+ auto sh = std::dynamic_pointer_cast<typename holder_type::element_type>(
1268
+ v_h.value_ptr<type>()->shared_from_this());
1269
+ if (sh) {
1270
+ new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(sh));
1271
+ v_h.set_holder_constructed();
1272
+ }
1273
+ } catch (const std::bad_weak_ptr &) {}
1274
+
1275
+ if (!v_h.holder_constructed() && inst->owned) {
1276
+ new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
1277
+ v_h.set_holder_constructed();
1278
+ }
1279
+ }
1280
+
1281
+ static void init_holder_from_existing(const detail::value_and_holder &v_h,
1282
+ const holder_type *holder_ptr, std::true_type /*is_copy_constructible*/) {
1283
+ new (std::addressof(v_h.holder<holder_type>())) holder_type(*reinterpret_cast<const holder_type *>(holder_ptr));
1284
+ }
1285
+
1286
+ static void init_holder_from_existing(const detail::value_and_holder &v_h,
1287
+ const holder_type *holder_ptr, std::false_type /*is_copy_constructible*/) {
1288
+ new (std::addressof(v_h.holder<holder_type>())) holder_type(std::move(*const_cast<holder_type *>(holder_ptr)));
1289
+ }
1290
+
1291
+ /// Initialize holder object, variant 2: try to construct from existing holder object, if possible
1292
+ static void init_holder(detail::instance *inst, detail::value_and_holder &v_h,
1293
+ const holder_type *holder_ptr, const void * /* dummy -- not enable_shared_from_this<T>) */) {
1294
+ if (holder_ptr) {
1295
+ init_holder_from_existing(v_h, holder_ptr, std::is_copy_constructible<holder_type>());
1296
+ v_h.set_holder_constructed();
1297
+ } else if (inst->owned || detail::always_construct_holder<holder_type>::value) {
1298
+ new (std::addressof(v_h.holder<holder_type>())) holder_type(v_h.value_ptr<type>());
1299
+ v_h.set_holder_constructed();
1300
+ }
1301
+ }
1302
+
1303
+ /// Performs instance initialization including constructing a holder and registering the known
1304
+ /// instance. Should be called as soon as the `type` value_ptr is set for an instance. Takes an
1305
+ /// optional pointer to an existing holder to use; if not specified and the instance is
1306
+ /// `.owned`, a new holder will be constructed to manage the value pointer.
1307
+ static void init_instance(detail::instance *inst, const void *holder_ptr) {
1308
+ auto v_h = inst->get_value_and_holder(detail::get_type_info(typeid(type)));
1309
+ if (!v_h.instance_registered()) {
1310
+ register_instance(inst, v_h.value_ptr(), v_h.type);
1311
+ v_h.set_instance_registered();
1312
+ }
1313
+ init_holder(inst, v_h, (const holder_type *) holder_ptr, v_h.value_ptr<type>());
1314
+ }
1315
+
1316
+ /// Deallocates an instance; via holder, if constructed; otherwise via operator delete.
1317
+ static void dealloc(detail::value_and_holder &v_h) {
1318
+ if (v_h.holder_constructed()) {
1319
+ v_h.holder<holder_type>().~holder_type();
1320
+ v_h.set_holder_constructed(false);
1321
+ }
1322
+ else {
1323
+ detail::call_operator_delete(v_h.value_ptr<type>(), v_h.type->type_size);
1324
+ }
1325
+ v_h.value_ptr() = nullptr;
1326
+ }
1327
+
1328
+ static detail::function_record *get_function_record(handle h) {
1329
+ h = detail::get_function(h);
1330
+ return h ? (detail::function_record *) reinterpret_borrow<capsule>(PyCFunction_GET_SELF(h.ptr()))
1331
+ : nullptr;
1332
+ }
1333
+ };
1334
+
1335
+ /// Binds an existing constructor taking arguments Args...
1336
+ template <typename... Args> detail::initimpl::constructor<Args...> init() { return {}; }
1337
+ /// Like `init<Args...>()`, but the instance is always constructed through the alias class (even
1338
+ /// when not inheriting on the Python side).
1339
+ template <typename... Args> detail::initimpl::alias_constructor<Args...> init_alias() { return {}; }
1340
+
1341
+ /// Binds a factory function as a constructor
1342
+ template <typename Func, typename Ret = detail::initimpl::factory<Func>>
1343
+ Ret init(Func &&f) { return {std::forward<Func>(f)}; }
1344
+
1345
+ /// Dual-argument factory function: the first function is called when no alias is needed, the second
1346
+ /// when an alias is needed (i.e. due to python-side inheritance). Arguments must be identical.
1347
+ template <typename CFunc, typename AFunc, typename Ret = detail::initimpl::factory<CFunc, AFunc>>
1348
+ Ret init(CFunc &&c, AFunc &&a) {
1349
+ return {std::forward<CFunc>(c), std::forward<AFunc>(a)};
1350
+ }
1351
+
1352
+ /// Binds pickling functions `__getstate__` and `__setstate__` and ensures that the type
1353
+ /// returned by `__getstate__` is the same as the argument accepted by `__setstate__`.
1354
+ template <typename GetState, typename SetState>
1355
+ detail::initimpl::pickle_factory<GetState, SetState> pickle(GetState &&g, SetState &&s) {
1356
+ return {std::forward<GetState>(g), std::forward<SetState>(s)};
1357
+ }
1358
+
1359
+ /// Binds C++ enumerations and enumeration classes to Python
1360
+ template <typename Type> class enum_ : public class_<Type> {
1361
+ public:
1362
+ using class_<Type>::def;
1363
+ using class_<Type>::def_property_readonly_static;
1364
+ using Scalar = typename std::underlying_type<Type>::type;
1365
+
1366
+ template <typename... Extra>
1367
+ enum_(const handle &scope, const char *name, const Extra&... extra)
1368
+ : class_<Type>(scope, name, extra...), m_entries(), m_parent(scope) {
1369
+
1370
+ constexpr bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>::value;
1371
+
1372
+ auto m_entries_ptr = m_entries.inc_ref().ptr();
1373
+ def("__repr__", [name, m_entries_ptr](Type value) -> pybind11::str {
1374
+ for (const auto &kv : reinterpret_borrow<dict>(m_entries_ptr)) {
1375
+ if (pybind11::cast<Type>(kv.second) == value)
1376
+ return pybind11::str("{}.{}").format(name, kv.first);
1377
+ }
1378
+ return pybind11::str("{}.???").format(name);
1379
+ });
1380
+ def_property_readonly_static("__members__", [m_entries_ptr](object /* self */) {
1381
+ dict m;
1382
+ for (const auto &kv : reinterpret_borrow<dict>(m_entries_ptr))
1383
+ m[kv.first] = kv.second;
1384
+ return m;
1385
+ }, return_value_policy::copy);
1386
+ def(init([](Scalar i) { return static_cast<Type>(i); }));
1387
+ def("__int__", [](Type value) { return (Scalar) value; });
1388
+ #if PY_MAJOR_VERSION < 3
1389
+ def("__long__", [](Type value) { return (Scalar) value; });
1390
+ #endif
1391
+ def("__eq__", [](const Type &value, Type *value2) { return value2 && value == *value2; });
1392
+ def("__ne__", [](const Type &value, Type *value2) { return !value2 || value != *value2; });
1393
+ if (is_arithmetic) {
1394
+ def("__lt__", [](const Type &value, Type *value2) { return value2 && value < *value2; });
1395
+ def("__gt__", [](const Type &value, Type *value2) { return value2 && value > *value2; });
1396
+ def("__le__", [](const Type &value, Type *value2) { return value2 && value <= *value2; });
1397
+ def("__ge__", [](const Type &value, Type *value2) { return value2 && value >= *value2; });
1398
+ }
1399
+ if (std::is_convertible<Type, Scalar>::value) {
1400
+ // Don't provide comparison with the underlying type if the enum isn't convertible,
1401
+ // i.e. if Type is a scoped enum, mirroring the C++ behaviour. (NB: we explicitly
1402
+ // convert Type to Scalar below anyway because this needs to compile).
1403
+ def("__eq__", [](const Type &value, Scalar value2) { return (Scalar) value == value2; });
1404
+ def("__ne__", [](const Type &value, Scalar value2) { return (Scalar) value != value2; });
1405
+ if (is_arithmetic) {
1406
+ def("__lt__", [](const Type &value, Scalar value2) { return (Scalar) value < value2; });
1407
+ def("__gt__", [](const Type &value, Scalar value2) { return (Scalar) value > value2; });
1408
+ def("__le__", [](const Type &value, Scalar value2) { return (Scalar) value <= value2; });
1409
+ def("__ge__", [](const Type &value, Scalar value2) { return (Scalar) value >= value2; });
1410
+ def("__invert__", [](const Type &value) { return ~((Scalar) value); });
1411
+ def("__and__", [](const Type &value, Scalar value2) { return (Scalar) value & value2; });
1412
+ def("__or__", [](const Type &value, Scalar value2) { return (Scalar) value | value2; });
1413
+ def("__xor__", [](const Type &value, Scalar value2) { return (Scalar) value ^ value2; });
1414
+ def("__rand__", [](const Type &value, Scalar value2) { return (Scalar) value & value2; });
1415
+ def("__ror__", [](const Type &value, Scalar value2) { return (Scalar) value | value2; });
1416
+ def("__rxor__", [](const Type &value, Scalar value2) { return (Scalar) value ^ value2; });
1417
+ def("__and__", [](const Type &value, const Type &value2) { return (Scalar) value & (Scalar) value2; });
1418
+ def("__or__", [](const Type &value, const Type &value2) { return (Scalar) value | (Scalar) value2; });
1419
+ def("__xor__", [](const Type &value, const Type &value2) { return (Scalar) value ^ (Scalar) value2; });
1420
+ }
1421
+ }
1422
+ def("__hash__", [](const Type &value) { return (Scalar) value; });
1423
+ // Pickling and unpickling -- needed for use with the 'multiprocessing' module
1424
+ def(pickle([](const Type &value) { return pybind11::make_tuple((Scalar) value); },
1425
+ [](tuple t) { return static_cast<Type>(t[0].cast<Scalar>()); }));
1426
+ }
1427
+
1428
+ /// Export enumeration entries into the parent scope
1429
+ enum_& export_values() {
1430
+ for (const auto &kv : m_entries)
1431
+ m_parent.attr(kv.first) = kv.second;
1432
+ return *this;
1433
+ }
1434
+
1435
+ /// Add an enumeration entry
1436
+ enum_& value(char const* name, Type value) {
1437
+ auto v = pybind11::cast(value, return_value_policy::copy);
1438
+ this->attr(name) = v;
1439
+ m_entries[pybind11::str(name)] = v;
1440
+ return *this;
1441
+ }
1442
+
1443
+ private:
1444
+ dict m_entries;
1445
+ handle m_parent;
1446
+ };
1447
+
1448
+ NAMESPACE_BEGIN(detail)
1449
+
1450
+
1451
+ inline void keep_alive_impl(handle nurse, handle patient) {
1452
+ if (!nurse || !patient)
1453
+ pybind11_fail("Could not activate keep_alive!");
1454
+
1455
+ if (patient.is_none() || nurse.is_none())
1456
+ return; /* Nothing to keep alive or nothing to be kept alive by */
1457
+
1458
+ auto tinfo = all_type_info(Py_TYPE(nurse.ptr()));
1459
+ if (!tinfo.empty()) {
1460
+ /* It's a pybind-registered type, so we can store the patient in the
1461
+ * internal list. */
1462
+ add_patient(nurse.ptr(), patient.ptr());
1463
+ }
1464
+ else {
1465
+ /* Fall back to clever approach based on weak references taken from
1466
+ * Boost.Python. This is not used for pybind-registered types because
1467
+ * the objects can be destroyed out-of-order in a GC pass. */
1468
+ cpp_function disable_lifesupport(
1469
+ [patient](handle weakref) { patient.dec_ref(); weakref.dec_ref(); });
1470
+
1471
+ weakref wr(nurse, disable_lifesupport);
1472
+
1473
+ patient.inc_ref(); /* reference patient and leak the weak reference */
1474
+ (void) wr.release();
1475
+ }
1476
+ }
1477
+
1478
+ PYBIND11_NOINLINE inline void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret) {
1479
+ auto get_arg = [&](size_t n) {
1480
+ if (n == 0)
1481
+ return ret;
1482
+ else if (n == 1 && call.init_self)
1483
+ return call.init_self;
1484
+ else if (n <= call.args.size())
1485
+ return call.args[n - 1];
1486
+ return handle();
1487
+ };
1488
+
1489
+ keep_alive_impl(get_arg(Nurse), get_arg(Patient));
1490
+ }
1491
+
1492
+ inline std::pair<decltype(internals::registered_types_py)::iterator, bool> all_type_info_get_cache(PyTypeObject *type) {
1493
+ auto res = get_internals().registered_types_py
1494
+ #ifdef __cpp_lib_unordered_map_try_emplace
1495
+ .try_emplace(type);
1496
+ #else
1497
+ .emplace(type, std::vector<detail::type_info *>());
1498
+ #endif
1499
+ if (res.second) {
1500
+ // New cache entry created; set up a weak reference to automatically remove it if the type
1501
+ // gets destroyed:
1502
+ weakref((PyObject *) type, cpp_function([type](handle wr) {
1503
+ get_internals().registered_types_py.erase(type);
1504
+ wr.dec_ref();
1505
+ })).release();
1506
+ }
1507
+
1508
+ return res;
1509
+ }
1510
+
1511
+ template <typename Iterator, typename Sentinel, bool KeyIterator, return_value_policy Policy>
1512
+ struct iterator_state {
1513
+ Iterator it;
1514
+ Sentinel end;
1515
+ bool first_or_done;
1516
+ };
1517
+
1518
+ NAMESPACE_END(detail)
1519
+
1520
+ /// Makes a python iterator from a first and past-the-end C++ InputIterator.
1521
+ template <return_value_policy Policy = return_value_policy::reference_internal,
1522
+ typename Iterator,
1523
+ typename Sentinel,
1524
+ typename ValueType = decltype(*std::declval<Iterator>()),
1525
+ typename... Extra>
1526
+ iterator make_iterator(Iterator first, Sentinel last, Extra &&... extra) {
1527
+ typedef detail::iterator_state<Iterator, Sentinel, false, Policy> state;
1528
+
1529
+ if (!detail::get_type_info(typeid(state), false)) {
1530
+ class_<state>(handle(), "iterator", pybind11::module_local())
1531
+ .def("__iter__", [](state &s) -> state& { return s; })
1532
+ .def("__next__", [](state &s) -> ValueType {
1533
+ if (!s.first_or_done)
1534
+ ++s.it;
1535
+ else
1536
+ s.first_or_done = false;
1537
+ if (s.it == s.end) {
1538
+ s.first_or_done = true;
1539
+ throw stop_iteration();
1540
+ }
1541
+ return *s.it;
1542
+ }, std::forward<Extra>(extra)..., Policy);
1543
+ }
1544
+
1545
+ return cast(state{first, last, true});
1546
+ }
1547
+
1548
+ /// Makes an python iterator over the keys (`.first`) of a iterator over pairs from a
1549
+ /// first and past-the-end InputIterator.
1550
+ template <return_value_policy Policy = return_value_policy::reference_internal,
1551
+ typename Iterator,
1552
+ typename Sentinel,
1553
+ typename KeyType = decltype((*std::declval<Iterator>()).first),
1554
+ typename... Extra>
1555
+ iterator make_key_iterator(Iterator first, Sentinel last, Extra &&... extra) {
1556
+ typedef detail::iterator_state<Iterator, Sentinel, true, Policy> state;
1557
+
1558
+ if (!detail::get_type_info(typeid(state), false)) {
1559
+ class_<state>(handle(), "iterator", pybind11::module_local())
1560
+ .def("__iter__", [](state &s) -> state& { return s; })
1561
+ .def("__next__", [](state &s) -> KeyType {
1562
+ if (!s.first_or_done)
1563
+ ++s.it;
1564
+ else
1565
+ s.first_or_done = false;
1566
+ if (s.it == s.end) {
1567
+ s.first_or_done = true;
1568
+ throw stop_iteration();
1569
+ }
1570
+ return (*s.it).first;
1571
+ }, std::forward<Extra>(extra)..., Policy);
1572
+ }
1573
+
1574
+ return cast(state{first, last, true});
1575
+ }
1576
+
1577
+ /// Makes an iterator over values of an stl container or other container supporting
1578
+ /// `std::begin()`/`std::end()`
1579
+ template <return_value_policy Policy = return_value_policy::reference_internal,
1580
+ typename Type, typename... Extra> iterator make_iterator(Type &value, Extra&&... extra) {
1581
+ return make_iterator<Policy>(std::begin(value), std::end(value), extra...);
1582
+ }
1583
+
1584
+ /// Makes an iterator over the keys (`.first`) of a stl map-like container supporting
1585
+ /// `std::begin()`/`std::end()`
1586
+ template <return_value_policy Policy = return_value_policy::reference_internal,
1587
+ typename Type, typename... Extra> iterator make_key_iterator(Type &value, Extra&&... extra) {
1588
+ return make_key_iterator<Policy>(std::begin(value), std::end(value), extra...);
1589
+ }
1590
+
1591
+ template <typename InputType, typename OutputType> void implicitly_convertible() {
1592
+ struct set_flag {
1593
+ bool &flag;
1594
+ set_flag(bool &flag) : flag(flag) { flag = true; }
1595
+ ~set_flag() { flag = false; }
1596
+ };
1597
+ auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * {
1598
+ static bool currently_used = false;
1599
+ if (currently_used) // implicit conversions are non-reentrant
1600
+ return nullptr;
1601
+ set_flag flag_helper(currently_used);
1602
+ if (!detail::make_caster<InputType>().load(obj, false))
1603
+ return nullptr;
1604
+ tuple args(1);
1605
+ args[0] = obj;
1606
+ PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr);
1607
+ if (result == nullptr)
1608
+ PyErr_Clear();
1609
+ return result;
1610
+ };
1611
+
1612
+ if (auto tinfo = detail::get_type_info(typeid(OutputType)))
1613
+ tinfo->implicit_conversions.push_back(implicit_caster);
1614
+ else
1615
+ pybind11_fail("implicitly_convertible: Unable to find type " + type_id<OutputType>());
1616
+ }
1617
+
1618
+ template <typename ExceptionTranslator>
1619
+ void register_exception_translator(ExceptionTranslator&& translator) {
1620
+ detail::get_internals().registered_exception_translators.push_front(
1621
+ std::forward<ExceptionTranslator>(translator));
1622
+ }
1623
+
1624
+ /**
1625
+ * Wrapper to generate a new Python exception type.
1626
+ *
1627
+ * This should only be used with PyErr_SetString for now.
1628
+ * It is not (yet) possible to use as a py::base.
1629
+ * Template type argument is reserved for future use.
1630
+ */
1631
+ template <typename type>
1632
+ class exception : public object {
1633
+ public:
1634
+ exception() = default;
1635
+ exception(handle scope, const char *name, PyObject *base = PyExc_Exception) {
1636
+ std::string full_name = scope.attr("__name__").cast<std::string>() +
1637
+ std::string(".") + name;
1638
+ m_ptr = PyErr_NewException(const_cast<char *>(full_name.c_str()), base, NULL);
1639
+ if (hasattr(scope, name))
1640
+ pybind11_fail("Error during initialization: multiple incompatible "
1641
+ "definitions with name \"" + std::string(name) + "\"");
1642
+ scope.attr(name) = *this;
1643
+ }
1644
+
1645
+ // Sets the current python exception to this exception object with the given message
1646
+ void operator()(const char *message) {
1647
+ PyErr_SetString(m_ptr, message);
1648
+ }
1649
+ };
1650
+
1651
+ NAMESPACE_BEGIN(detail)
1652
+ // Returns a reference to a function-local static exception object used in the simple
1653
+ // register_exception approach below. (It would be simpler to have the static local variable
1654
+ // directly in register_exception, but that makes clang <3.5 segfault - issue #1349).
1655
+ template <typename CppException>
1656
+ exception<CppException> &get_exception_object() { static exception<CppException> ex; return ex; }
1657
+ NAMESPACE_END(detail)
1658
+
1659
+ /**
1660
+ * Registers a Python exception in `m` of the given `name` and installs an exception translator to
1661
+ * translate the C++ exception to the created Python exception using the exceptions what() method.
1662
+ * This is intended for simple exception translations; for more complex translation, register the
1663
+ * exception object and translator directly.
1664
+ */
1665
+ template <typename CppException>
1666
+ exception<CppException> &register_exception(handle scope,
1667
+ const char *name,
1668
+ PyObject *base = PyExc_Exception) {
1669
+ auto &ex = detail::get_exception_object<CppException>();
1670
+ if (!ex) ex = exception<CppException>(scope, name, base);
1671
+
1672
+ register_exception_translator([](std::exception_ptr p) {
1673
+ if (!p) return;
1674
+ try {
1675
+ std::rethrow_exception(p);
1676
+ } catch (const CppException &e) {
1677
+ detail::get_exception_object<CppException>()(e.what());
1678
+ }
1679
+ });
1680
+ return ex;
1681
+ }
1682
+
1683
+ NAMESPACE_BEGIN(detail)
1684
+ PYBIND11_NOINLINE inline void print(tuple args, dict kwargs) {
1685
+ auto strings = tuple(args.size());
1686
+ for (size_t i = 0; i < args.size(); ++i) {
1687
+ strings[i] = str(args[i]);
1688
+ }
1689
+ auto sep = kwargs.contains("sep") ? kwargs["sep"] : cast(" ");
1690
+ auto line = sep.attr("join")(strings);
1691
+
1692
+ object file;
1693
+ if (kwargs.contains("file")) {
1694
+ file = kwargs["file"].cast<object>();
1695
+ } else {
1696
+ try {
1697
+ file = module::import("sys").attr("stdout");
1698
+ } catch (const error_already_set &) {
1699
+ /* If print() is called from code that is executed as
1700
+ part of garbage collection during interpreter shutdown,
1701
+ importing 'sys' can fail. Give up rather than crashing the
1702
+ interpreter in this case. */
1703
+ return;
1704
+ }
1705
+ }
1706
+
1707
+ auto write = file.attr("write");
1708
+ write(line);
1709
+ write(kwargs.contains("end") ? kwargs["end"] : cast("\n"));
1710
+
1711
+ if (kwargs.contains("flush") && kwargs["flush"].cast<bool>())
1712
+ file.attr("flush")();
1713
+ }
1714
+ NAMESPACE_END(detail)
1715
+
1716
+ template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
1717
+ void print(Args &&...args) {
1718
+ auto c = detail::collect_arguments<policy>(std::forward<Args>(args)...);
1719
+ detail::print(c.args(), c.kwargs());
1720
+ }
1721
+
1722
+ #if defined(WITH_THREAD) && !defined(PYPY_VERSION)
1723
+
1724
+ /* The functions below essentially reproduce the PyGILState_* API using a RAII
1725
+ * pattern, but there are a few important differences:
1726
+ *
1727
+ * 1. When acquiring the GIL from an non-main thread during the finalization
1728
+ * phase, the GILState API blindly terminates the calling thread, which
1729
+ * is often not what is wanted. This API does not do this.
1730
+ *
1731
+ * 2. The gil_scoped_release function can optionally cut the relationship
1732
+ * of a PyThreadState and its associated thread, which allows moving it to
1733
+ * another thread (this is a fairly rare/advanced use case).
1734
+ *
1735
+ * 3. The reference count of an acquired thread state can be controlled. This
1736
+ * can be handy to prevent cases where callbacks issued from an external
1737
+ * thread would otherwise constantly construct and destroy thread state data
1738
+ * structures.
1739
+ *
1740
+ * See the Python bindings of NanoGUI (http://github.com/wjakob/nanogui) for an
1741
+ * example which uses features 2 and 3 to migrate the Python thread of
1742
+ * execution to another thread (to run the event loop on the original thread,
1743
+ * in this case).
1744
+ */
1745
+
1746
+ class gil_scoped_acquire {
1747
+ public:
1748
+ PYBIND11_NOINLINE gil_scoped_acquire() {
1749
+ auto const &internals = detail::get_internals();
1750
+ tstate = (PyThreadState *) PYBIND11_TLS_GET_VALUE(internals.tstate);
1751
+
1752
+ if (!tstate) {
1753
+ tstate = PyThreadState_New(internals.istate);
1754
+ #if !defined(NDEBUG)
1755
+ if (!tstate)
1756
+ pybind11_fail("scoped_acquire: could not create thread state!");
1757
+ #endif
1758
+ tstate->gilstate_counter = 0;
1759
+ PYBIND11_TLS_REPLACE_VALUE(internals.tstate, tstate);
1760
+ } else {
1761
+ release = detail::get_thread_state_unchecked() != tstate;
1762
+ }
1763
+
1764
+ if (release) {
1765
+ /* Work around an annoying assertion in PyThreadState_Swap */
1766
+ #if defined(Py_DEBUG)
1767
+ PyInterpreterState *interp = tstate->interp;
1768
+ tstate->interp = nullptr;
1769
+ #endif
1770
+ PyEval_AcquireThread(tstate);
1771
+ #if defined(Py_DEBUG)
1772
+ tstate->interp = interp;
1773
+ #endif
1774
+ }
1775
+
1776
+ inc_ref();
1777
+ }
1778
+
1779
+ void inc_ref() {
1780
+ ++tstate->gilstate_counter;
1781
+ }
1782
+
1783
+ PYBIND11_NOINLINE void dec_ref() {
1784
+ --tstate->gilstate_counter;
1785
+ #if !defined(NDEBUG)
1786
+ if (detail::get_thread_state_unchecked() != tstate)
1787
+ pybind11_fail("scoped_acquire::dec_ref(): thread state must be current!");
1788
+ if (tstate->gilstate_counter < 0)
1789
+ pybind11_fail("scoped_acquire::dec_ref(): reference count underflow!");
1790
+ #endif
1791
+ if (tstate->gilstate_counter == 0) {
1792
+ #if !defined(NDEBUG)
1793
+ if (!release)
1794
+ pybind11_fail("scoped_acquire::dec_ref(): internal error!");
1795
+ #endif
1796
+ PyThreadState_Clear(tstate);
1797
+ PyThreadState_DeleteCurrent();
1798
+ PYBIND11_TLS_DELETE_VALUE(detail::get_internals().tstate);
1799
+ release = false;
1800
+ }
1801
+ }
1802
+
1803
+ PYBIND11_NOINLINE ~gil_scoped_acquire() {
1804
+ dec_ref();
1805
+ if (release)
1806
+ PyEval_SaveThread();
1807
+ }
1808
+ private:
1809
+ PyThreadState *tstate = nullptr;
1810
+ bool release = true;
1811
+ };
1812
+
1813
+ class gil_scoped_release {
1814
+ public:
1815
+ explicit gil_scoped_release(bool disassoc = false) : disassoc(disassoc) {
1816
+ // `get_internals()` must be called here unconditionally in order to initialize
1817
+ // `internals.tstate` for subsequent `gil_scoped_acquire` calls. Otherwise, an
1818
+ // initialization race could occur as multiple threads try `gil_scoped_acquire`.
1819
+ const auto &internals = detail::get_internals();
1820
+ tstate = PyEval_SaveThread();
1821
+ if (disassoc) {
1822
+ auto key = internals.tstate;
1823
+ PYBIND11_TLS_DELETE_VALUE(key);
1824
+ }
1825
+ }
1826
+ ~gil_scoped_release() {
1827
+ if (!tstate)
1828
+ return;
1829
+ PyEval_RestoreThread(tstate);
1830
+ if (disassoc) {
1831
+ auto key = detail::get_internals().tstate;
1832
+ PYBIND11_TLS_REPLACE_VALUE(key, tstate);
1833
+ }
1834
+ }
1835
+ private:
1836
+ PyThreadState *tstate;
1837
+ bool disassoc;
1838
+ };
1839
+ #elif defined(PYPY_VERSION)
1840
+ class gil_scoped_acquire {
1841
+ PyGILState_STATE state;
1842
+ public:
1843
+ gil_scoped_acquire() { state = PyGILState_Ensure(); }
1844
+ ~gil_scoped_acquire() { PyGILState_Release(state); }
1845
+ };
1846
+
1847
+ class gil_scoped_release {
1848
+ PyThreadState *state;
1849
+ public:
1850
+ gil_scoped_release() { state = PyEval_SaveThread(); }
1851
+ ~gil_scoped_release() { PyEval_RestoreThread(state); }
1852
+ };
1853
+ #else
1854
+ class gil_scoped_acquire { };
1855
+ class gil_scoped_release { };
1856
+ #endif
1857
+
1858
+ error_already_set::~error_already_set() {
1859
+ if (type) {
1860
+ error_scope scope;
1861
+ gil_scoped_acquire gil;
1862
+ type.release().dec_ref();
1863
+ value.release().dec_ref();
1864
+ trace.release().dec_ref();
1865
+ }
1866
+ }
1867
+
1868
+ inline function get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name) {
1869
+ handle self = detail::get_object_handle(this_ptr, this_type);
1870
+ if (!self)
1871
+ return function();
1872
+ handle type = self.get_type();
1873
+ auto key = std::make_pair(type.ptr(), name);
1874
+
1875
+ /* Cache functions that aren't overloaded in Python to avoid
1876
+ many costly Python dictionary lookups below */
1877
+ auto &cache = detail::get_internals().inactive_overload_cache;
1878
+ if (cache.find(key) != cache.end())
1879
+ return function();
1880
+
1881
+ function overload = getattr(self, name, function());
1882
+ if (overload.is_cpp_function()) {
1883
+ cache.insert(key);
1884
+ return function();
1885
+ }
1886
+
1887
+ /* Don't call dispatch code if invoked from overridden function.
1888
+ Unfortunately this doesn't work on PyPy. */
1889
+ #if !defined(PYPY_VERSION)
1890
+ PyFrameObject *frame = PyThreadState_Get()->frame;
1891
+ if (frame && (std::string) str(frame->f_code->co_name) == name &&
1892
+ frame->f_code->co_argcount > 0) {
1893
+ PyFrame_FastToLocals(frame);
1894
+ PyObject *self_caller = PyDict_GetItem(
1895
+ frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
1896
+ if (self_caller == self.ptr())
1897
+ return function();
1898
+ }
1899
+ #else
1900
+ /* PyPy currently doesn't provide a detailed cpyext emulation of
1901
+ frame objects, so we have to emulate this using Python. This
1902
+ is going to be slow..*/
1903
+ dict d; d["self"] = self; d["name"] = pybind11::str(name);
1904
+ PyObject *result = PyRun_String(
1905
+ "import inspect\n"
1906
+ "frame = inspect.currentframe()\n"
1907
+ "if frame is not None:\n"
1908
+ " frame = frame.f_back\n"
1909
+ " if frame is not None and str(frame.f_code.co_name) == name and "
1910
+ "frame.f_code.co_argcount > 0:\n"
1911
+ " self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n"
1912
+ " if self_caller == self:\n"
1913
+ " self = None\n",
1914
+ Py_file_input, d.ptr(), d.ptr());
1915
+ if (result == nullptr)
1916
+ throw error_already_set();
1917
+ if (d["self"].is_none())
1918
+ return function();
1919
+ Py_DECREF(result);
1920
+ #endif
1921
+
1922
+ return overload;
1923
+ }
1924
+
1925
+ template <class T> function get_overload(const T *this_ptr, const char *name) {
1926
+ auto tinfo = detail::get_type_info(typeid(T));
1927
+ return tinfo ? get_type_overload(this_ptr, tinfo, name) : function();
1928
+ }
1929
+
1930
+ #define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) { \
1931
+ pybind11::gil_scoped_acquire gil; \
1932
+ pybind11::function overload = pybind11::get_overload(static_cast<const cname *>(this), name); \
1933
+ if (overload) { \
1934
+ auto o = overload(__VA_ARGS__); \
1935
+ if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) { \
1936
+ static pybind11::detail::overload_caster_t<ret_type> caster; \
1937
+ return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \
1938
+ } \
1939
+ else return pybind11::detail::cast_safe<ret_type>(std::move(o)); \
1940
+ } \
1941
+ }
1942
+
1943
+ #define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
1944
+ PYBIND11_OVERLOAD_INT(ret_type, cname, name, __VA_ARGS__) \
1945
+ return cname::fn(__VA_ARGS__)
1946
+
1947
+ #define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
1948
+ PYBIND11_OVERLOAD_INT(ret_type, cname, name, __VA_ARGS__) \
1949
+ pybind11::pybind11_fail("Tried to call pure virtual function \"" #cname "::" name "\"");
1950
+
1951
+ #define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
1952
+ PYBIND11_OVERLOAD_NAME(ret_type, cname, #fn, fn, __VA_ARGS__)
1953
+
1954
+ #define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
1955
+ PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, #fn, fn, __VA_ARGS__)
1956
+
1957
+ NAMESPACE_END(PYBIND11_NAMESPACE)
1958
+
1959
+ #if defined(_MSC_VER)
1960
+ # pragma warning(pop)
1961
+ #elif defined(__INTEL_COMPILER)
1962
+ /* Leave ignored warnings on */
1963
+ #elif defined(__GNUG__) && !defined(__clang__)
1964
+ # pragma GCC diagnostic pop
1965
+ #endif