OLD | NEW |
(Empty) | |
| 1 // Copyright 2014 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 #include "mojo/public/python/src/python_system_helper.h" |
| 6 |
| 7 #include "Python.h" |
| 8 |
| 9 #include "mojo/public/cpp/environment/logging.h" |
| 10 #include "mojo/public/cpp/system/macros.h" |
| 11 #include "mojo/public/cpp/utility/run_loop.h" |
| 12 |
| 13 namespace { |
| 14 |
| 15 class ScopedGIL { |
| 16 public: |
| 17 ScopedGIL() { |
| 18 state_ = PyGILState_Ensure(); |
| 19 } |
| 20 |
| 21 ~ScopedGIL() { |
| 22 PyGILState_Release(state_); |
| 23 } |
| 24 |
| 25 private: |
| 26 PyGILState_STATE state_; |
| 27 |
| 28 MOJO_DISALLOW_COPY_AND_ASSIGN(ScopedGIL); |
| 29 }; |
| 30 |
| 31 class PythonClosure : public mojo::Closure::Runnable { |
| 32 public: |
| 33 PythonClosure(PyObject* callable) : callable_(callable) { |
| 34 MOJO_CHECK(callable); |
| 35 Py_XINCREF(callable); |
| 36 } |
| 37 |
| 38 virtual ~PythonClosure() { |
| 39 ScopedGIL acquire_gil; |
| 40 Py_DECREF(callable_); |
| 41 } |
| 42 |
| 43 virtual void Run() const MOJO_OVERRIDE { |
| 44 ScopedGIL acquire_gil; |
| 45 PyObject* empty_tuple = PyTuple_New(0); |
| 46 if (!empty_tuple) { |
| 47 mojo::RunLoop::current()->Quit(); |
| 48 return; |
| 49 } |
| 50 |
| 51 PyObject* result = PyObject_CallObject(callable_, empty_tuple); |
| 52 Py_DECREF(empty_tuple); |
| 53 if (result) { |
| 54 Py_DECREF(result); |
| 55 } else { |
| 56 mojo::RunLoop::current()->Quit(); |
| 57 return; |
| 58 } |
| 59 } |
| 60 |
| 61 private: |
| 62 PyObject* callable_; |
| 63 |
| 64 MOJO_DISALLOW_COPY_AND_ASSIGN(PythonClosure); |
| 65 }; |
| 66 |
| 67 } // namespace |
| 68 |
| 69 namespace mojo { |
| 70 |
| 71 Closure BuildClosure(PyObject* callable) { |
| 72 if (!PyCallable_Check(callable)) |
| 73 return Closure(); |
| 74 |
| 75 return Closure( |
| 76 static_cast<mojo::Closure::Runnable*>(new PythonClosure(callable))); |
| 77 } |
| 78 |
| 79 } // namespace mojo |
OLD | NEW |