test_callbacks.cpp 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. /*
  2. tests/test_callbacks.cpp -- callbacks
  3. Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
  4. All rights reserved. Use of this source code is governed by a
  5. BSD-style license that can be found in the LICENSE file.
  6. */
  7. #include "pybind11_tests.h"
  8. #include "constructor_stats.h"
  9. #include <pybind11/functional.h>
  10. #include <thread>
  11. int dummy_function(int i) { return i + 1; }
  12. TEST_SUBMODULE(callbacks, m) {
  13. // test_callbacks, test_function_signatures
  14. m.def("test_callback1", [](py::object func) { return func(); });
  15. m.def("test_callback2", [](py::object func) { return func("Hello", 'x', true, 5); });
  16. m.def("test_callback3", [](const std::function<int(int)> &func) {
  17. return "func(43) = " + std::to_string(func(43)); });
  18. m.def("test_callback4", []() -> std::function<int(int)> { return [](int i) { return i+1; }; });
  19. m.def("test_callback5", []() {
  20. return py::cpp_function([](int i) { return i+1; }, py::arg("number"));
  21. });
  22. // test_keyword_args_and_generalized_unpacking
  23. m.def("test_tuple_unpacking", [](py::function f) {
  24. auto t1 = py::make_tuple(2, 3);
  25. auto t2 = py::make_tuple(5, 6);
  26. return f("positional", 1, *t1, 4, *t2);
  27. });
  28. m.def("test_dict_unpacking", [](py::function f) {
  29. auto d1 = py::dict("key"_a="value", "a"_a=1);
  30. auto d2 = py::dict();
  31. auto d3 = py::dict("b"_a=2);
  32. return f("positional", 1, **d1, **d2, **d3);
  33. });
  34. m.def("test_keyword_args", [](py::function f) {
  35. return f("x"_a=10, "y"_a=20);
  36. });
  37. m.def("test_unpacking_and_keywords1", [](py::function f) {
  38. auto args = py::make_tuple(2);
  39. auto kwargs = py::dict("d"_a=4);
  40. return f(1, *args, "c"_a=3, **kwargs);
  41. });
  42. m.def("test_unpacking_and_keywords2", [](py::function f) {
  43. auto kwargs1 = py::dict("a"_a=1);
  44. auto kwargs2 = py::dict("c"_a=3, "d"_a=4);
  45. return f("positional", *py::make_tuple(1), 2, *py::make_tuple(3, 4), 5,
  46. "key"_a="value", **kwargs1, "b"_a=2, **kwargs2, "e"_a=5);
  47. });
  48. m.def("test_unpacking_error1", [](py::function f) {
  49. auto kwargs = py::dict("x"_a=3);
  50. return f("x"_a=1, "y"_a=2, **kwargs); // duplicate ** after keyword
  51. });
  52. m.def("test_unpacking_error2", [](py::function f) {
  53. auto kwargs = py::dict("x"_a=3);
  54. return f(**kwargs, "x"_a=1); // duplicate keyword after **
  55. });
  56. m.def("test_arg_conversion_error1", [](py::function f) {
  57. f(234, UnregisteredType(), "kw"_a=567);
  58. });
  59. m.def("test_arg_conversion_error2", [](py::function f) {
  60. f(234, "expected_name"_a=UnregisteredType(), "kw"_a=567);
  61. });
  62. // test_lambda_closure_cleanup
  63. struct Payload {
  64. Payload() { print_default_created(this); }
  65. ~Payload() { print_destroyed(this); }
  66. Payload(const Payload &) { print_copy_created(this); }
  67. Payload(Payload &&) { print_move_created(this); }
  68. };
  69. // Export the payload constructor statistics for testing purposes:
  70. m.def("payload_cstats", &ConstructorStats::get<Payload>);
  71. /* Test cleanup of lambda closure */
  72. m.def("test_cleanup", []() -> std::function<void(void)> {
  73. Payload p;
  74. return [p]() {
  75. /* p should be cleaned up when the returned function is garbage collected */
  76. (void) p;
  77. };
  78. });
  79. // test_cpp_function_roundtrip
  80. /* Test if passing a function pointer from C++ -> Python -> C++ yields the original pointer */
  81. m.def("dummy_function", &dummy_function);
  82. m.def("dummy_function2", [](int i, int j) { return i + j; });
  83. m.def("roundtrip", [](std::function<int(int)> f, bool expect_none = false) {
  84. if (expect_none && f)
  85. throw std::runtime_error("Expected None to be converted to empty std::function");
  86. return f;
  87. }, py::arg("f"), py::arg("expect_none")=false);
  88. m.def("test_dummy_function", [](const std::function<int(int)> &f) -> std::string {
  89. using fn_type = int (*)(int);
  90. auto result = f.target<fn_type>();
  91. if (!result) {
  92. auto r = f(1);
  93. return "can't convert to function pointer: eval(1) = " + std::to_string(r);
  94. } else if (*result == dummy_function) {
  95. auto r = (*result)(1);
  96. return "matches dummy_function: eval(1) = " + std::to_string(r);
  97. } else {
  98. return "argument does NOT match dummy_function. This should never happen!";
  99. }
  100. });
  101. class AbstractBase {
  102. public:
  103. // [workaround(intel)] = default does not work here
  104. // Defaulting this destructor results in linking errors with the Intel compiler
  105. // (in Debug builds only, tested with icpc (ICC) 2021.1 Beta 20200827)
  106. virtual ~AbstractBase() {}; // NOLINT(modernize-use-equals-default)
  107. virtual unsigned int func() = 0;
  108. };
  109. m.def("func_accepting_func_accepting_base", [](std::function<double(AbstractBase&)>) { });
  110. struct MovableObject {
  111. bool valid = true;
  112. MovableObject() = default;
  113. MovableObject(const MovableObject &) = default;
  114. MovableObject &operator=(const MovableObject &) = default;
  115. MovableObject(MovableObject &&o) : valid(o.valid) { o.valid = false; }
  116. MovableObject &operator=(MovableObject &&o) {
  117. valid = o.valid;
  118. o.valid = false;
  119. return *this;
  120. }
  121. };
  122. py::class_<MovableObject>(m, "MovableObject");
  123. // test_movable_object
  124. m.def("callback_with_movable", [](std::function<void(MovableObject &)> f) {
  125. auto x = MovableObject();
  126. f(x); // lvalue reference shouldn't move out object
  127. return x.valid; // must still return `true`
  128. });
  129. // test_bound_method_callback
  130. struct CppBoundMethodTest {};
  131. py::class_<CppBoundMethodTest>(m, "CppBoundMethodTest")
  132. .def(py::init<>())
  133. .def("triple", [](CppBoundMethodTest &, int val) { return 3 * val; });
  134. // test async Python callbacks
  135. using callback_f = std::function<void(int)>;
  136. m.def("test_async_callback", [](callback_f f, py::list work) {
  137. // make detached thread that calls `f` with piece of work after a little delay
  138. auto start_f = [f](int j) {
  139. auto invoke_f = [f, j] {
  140. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  141. f(j);
  142. };
  143. auto t = std::thread(std::move(invoke_f));
  144. t.detach();
  145. };
  146. // spawn worker threads
  147. for (auto i : work)
  148. start_f(py::cast<int>(i));
  149. });
  150. }