Skip to content

Instantly share code, notes, and snippets.

@joankaradimov
Created December 13, 2022 16:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joankaradimov/5452f80c2618009e7a1c1ecdc3042c8a to your computer and use it in GitHub Desktop.
Save joankaradimov/5452f80c2618009e7a1c1ecdc3042c8a to your computer and use it in GitHub Desktop.
Python C API Example
#include <Python.h>
static PyObject* increment(PyObject* self, PyObject* args)
{
double value, unused;
if (!PyArg_ParseTuple(args, "dd", &value, &unused))
return NULL;
value += 42;
return Py_BuildValue("d", value);
}
static PyObject* add_len(PyObject* self, PyObject* args)
{
PyObject* arg;
if (!PyArg_ParseTuple(args, "O", &arg))
return NULL;
int len = PyDict_Size(arg);
PyDict_SetItemString(arg, "length", Py_BuildValue("i", len));
return arg;
}
static PyMethodDef PyCApiMethods[] =
{
{ "increment", increment, METH_VARARGS, "increment a number" },
{ "add_len", add_len, METH_VARARGS, "add the length of a dict to the dict" },
{ NULL, NULL, 0, NULL }
};
static struct PyModuleDef clientmodule = {
PyModuleDef_HEAD_INIT,
"pycapi", /* name of module */
"documentation goes here", /* module documentation, may be NULL */
-1, /* size of per-interpreter state of the module,
or -1 if the module keeps state in global variables. */
PyCApiMethods,
};
PyMODINIT_FUNC PyInit_pycapi(void)
{
return PyModule_Create(&clientmodule);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment