Created
July 25, 2023 05:34
-
-
Save pranavsharma/0d369087bbe0c67440c6af83fe570a57 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Author: Pranav Sharma | |
| #include <pybind11/pybind11.h> | |
| #include <pybind11/functional.h> | |
| #include <thread> | |
| #include <iostream> | |
| #include <chrono> | |
| #define STRINGIFY(x) #x | |
| #define MACRO_STRINGIFY(x) STRINGIFY(x) | |
| namespace py = pybind11; | |
| #include <pybind11/pybind11.h> | |
| using PyCallback = std::function<void()>; | |
| using CppCallback = std::function<void(void*)>; | |
| struct UserData { | |
| PyCallback py_callback; | |
| }; | |
| void Callback(void* user_data) { | |
| std::cout << "Inside CPP callback\n"; | |
| UserData* user_data_holder = reinterpret_cast<UserData*>(user_data); | |
| PyGILState_STATE gstate; | |
| gstate = PyGILState_Ensure(); | |
| user_data_holder->py_callback(); | |
| PyGILState_Release(gstate); | |
| } | |
| void RunAsync(CppCallback cpp_callback, void* user_data) { | |
| std::thread([=]() | |
| { | |
| std::cout << "Inside thread..sleeping\n"; | |
| std::this_thread::sleep_for(std::chrono::milliseconds(5000)); | |
| std::cout << "Inside thread...done sleeping, calling cpp callback\n"; | |
| if (cpp_callback) { | |
| cpp_callback(user_data); | |
| } | |
| }).join(); | |
| } | |
| PYBIND11_MODULE(test_python_callback, m) { | |
| m.def("run_async", [](PyCallback py_callback)->void{ | |
| auto user_data_holder = new UserData(); | |
| user_data_holder->py_callback = py_callback; | |
| { | |
| py::gil_scoped_release release; | |
| RunAsync(Callback, user_data_holder); | |
| } | |
| }); | |
| #ifdef VERSION_INFO | |
| m.attr("__version__") = MACRO_STRINGIFY(VERSION_INFO); | |
| #else | |
| m.attr("__version__") = "dev"; | |
| #endif | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment