Skip to content

Instantly share code, notes, and snippets.

@mazhe
Created January 14, 2015 14:01
Show Gist options
  • Save mazhe/42ea42faf23c544134bd to your computer and use it in GitHub Desktop.
Save mazhe/42ea42faf23c544134bd to your computer and use it in GitHub Desktop.
docopt.c placeholder
include <Python.h>
typedef void *docopt_t;
docopt_t
docopt(const char *doc, int argc, char *argv[], int help, const char *version, int options_first)
{
PyObject *module, *func, *args, *ret;
Py_Initialize();
module = PyImport_ImportModule("docopt");
if (module == NULL) {
fputs("Cannot load the docopt python module\n", stderr);
return NULL;
}
func = PyObject_GetAttrString(module, "docopt");
if (func == NULL || !PyCallable_Check(func)) {
fputs("Cannot find the docopt python function\n", stderr);
return NULL;
}
Py_XDECREF(func);
args = PyTuple_New(5);
PyTuple_SetItem(args, 0, PyUnicode_FromString(doc));
PyTuple_SetItem(args, 1, PyList_New(argc-1));
for (int i = 1; i < argc; i++) {
PyList_SetItem(
PyTuple_GetItem(args, 1),
i-1,
PyUnicode_FromString(argv[i]));
}
PyTuple_SetItem(args, 2, PyBool_FromLong(help));
PyTuple_SetItem(args, 3, version != NULL ? PyUnicode_FromString(version) : Py_None);
PyTuple_SetItem(args, 4, PyBool_FromLong(options_first));
ret = PyObject_CallObject(func, args);
Py_Finalize();
return ret;
}
const char *
docopt_get(docopt_t *arguments, const char *name)
{
PyObject *value;
value = PyDict_GetItemString((PyObject *)arguments, name);
if (value == NULL) {
return NULL;
}
return PyUnicode_DATA(value);
}
typedef void *docopt_t;
docopt_t
docopt(const char *, int, char *[], int, const char *, int);
const char *
docopt_get(docopt_t, const char *);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment