Created
October 11, 2019 16:02
-
-
Save JeffLabonte/eca62cf5b0008a70b10fa5fef69f243e to your computer and use it in GitHub Desktop.
This file contains 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
/* this code uses only C features */ | |
static PyObject * | |
foo(PyObject *self, PyObject *args) | |
{ | |
PyObject *cb; | |
// Receive a single argument which can be any Python object | |
// note: the object's reference count is NOT increased (but it's pinned by | |
// the argument tuple). | |
if (!PyArg_ParseTuple(args, "O", &cb)) { | |
return 0; | |
} | |
// determine whether the object is in fact callable | |
if (!PyCallable_Check(cb)) { | |
PyErr_SetString(PyExc_TypeError, "foo: a callable is required"); | |
return 0; | |
} | |
// call it (no arguments supplied) | |
// there are a whole bunch of other PyObject_Call* functions for when you want | |
// to supply arguments | |
PyObject *rv = PyObject_CallObject(cb, 0); | |
// if calling it returned 0, must return 0 to propagate the exception | |
if (!rv) return 0; | |
// otherwise, discard the object returned and return None | |
Py_CLEAR(rv); | |
Py_RETURN_NONE; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment