Created
December 13, 2022 16:35
-
-
Save joankaradimov/5452f80c2618009e7a1c1ecdc3042c8a to your computer and use it in GitHub Desktop.
Python C API Example
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
#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