/src/googleclouddebugger/python_callback.cc

https://github.com/GoogleCloudPlatform/cloud-debug-python · C++ · 69 lines · 36 code · 17 blank · 16 comment · 2 complexity · a28e35138892dd483740a67c5341851e MD5 · raw file

  1. /**
  2. * Copyright 2015 Google Inc. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. // Ensure that Python.h is included before any other header.
  17. #include "common.h"
  18. #include "python_callback.h"
  19. namespace devtools {
  20. namespace cdbg {
  21. PyTypeObject PythonCallback::python_type_ =
  22. DefaultTypeDefinition(CDBG_SCOPED_NAME("_Callback"));
  23. PyMethodDef PythonCallback::callback_method_def_ = {
  24. const_cast<char*>("Callback"), // ml_name
  25. reinterpret_cast<PyCFunction>(PythonCallback::Run), // ml_meth
  26. METH_NOARGS, // ml_flags
  27. const_cast<char*>("") // ml_doc
  28. };
  29. ScopedPyObject PythonCallback::Wrap(std::function<void()> callback) {
  30. ScopedPyObject callback_obj = NewNativePythonObject<PythonCallback>();
  31. py_object_cast<PythonCallback>(callback_obj.get())->callback_ = callback;
  32. ScopedPyObject callback_method(PyCFunction_NewEx(
  33. &callback_method_def_,
  34. callback_obj.get(),
  35. GetDebugletModule()));
  36. return callback_method;
  37. }
  38. void PythonCallback::Disable(PyObject* method) {
  39. DCHECK(PyCFunction_Check(method));
  40. auto instance = py_object_cast<PythonCallback>(PyCFunction_GET_SELF(method));
  41. DCHECK(instance);
  42. instance->callback_ = nullptr;
  43. }
  44. PyObject* PythonCallback::Run(PyObject* self) {
  45. auto instance = py_object_cast<PythonCallback>(self);
  46. if (instance->callback_ != nullptr) {
  47. instance->callback_();
  48. }
  49. Py_RETURN_NONE;
  50. }
  51. } // namespace cdbg
  52. } // namespace devtools