amend bash.h; add example_builtin.c

This commit is contained in:
2025-06-01 07:51:03 -07:00
parent 424c8b0fee
commit e1202ab4fe
2 changed files with 23 additions and 26 deletions

47
bash.h
View File

@ -34,32 +34,29 @@ extern char **make_builtin_argv(WORD_LIST*, int*);
PyImport_AppendInittab(#modname, PyInit_##modname); \ PyImport_AppendInittab(#modname, PyInit_##modname); \
Py_Initialize(); \ Py_Initialize(); \
} \ } \
int _##bash_name(int argc, char **argv) { \ int ret = 1; \
int ret = 1; \ PyObject *mod = NULL, *func = NULL, *result; \
PyObject *mod = NULL, *func = NULL, *result; \ \
\ mod = PyImport_ImportModule(#modname); \
mod = PyImport_ImportModule(#modname); \ func = PyObject_GetAttrString(mod, #function); \
func = PyObject_GetAttrString(mod, #function); \ \
\ PyObject *py_argv = PyTuple_New(argc - 1); \
PyObject *py_argv = PyTuple_New(argc - 1); \ \
\ for (int i = 1; i < argc; i++) { \
for (int i = 1; i < argc; i++) { \ PyObject *arg_as_str = PyUnicode_FromString(argv[i]); \
PyObject *arg_as_str = PyUnicode_FromString(argv[i]); \ PyTuple_SetItem(py_argv, i-1, arg_as_str); \
PyTuple_SetItem(py_argv, i-1, arg_as_str); \
} \
\
result = PyObject_CallObject(func, py_argv); \
if (!result) { PyErr_Print(); goto finally; } \
ret = (int) PyFloat_AsDouble(result); \
\
finally: \
Py_XDECREF(result); \
Py_XDECREF(py_argv); \
Py_XDECREF(func); \
Py_XDECREF(mod); \
return ret; \
} \ } \
return _##bash_name(argc, argv); \ \
result = PyObject_CallObject(func, py_argv); \
if (!result) { PyErr_Print(); goto finally; } \
ret = (int) PyFloat_AsDouble(result); \
\
finally: \
Py_XDECREF(result); \
Py_XDECREF(py_argv); \
Py_XDECREF(func); \
Py_XDECREF(mod); \
return ret; \
} \ } \
WRAP_FUNC_WITH_BUILTIN(bash_name); \ WRAP_FUNC_WITH_BUILTIN(bash_name); \
DEFINE_BUILTIN(bash_name); DEFINE_BUILTIN(bash_name);

View File

@ -3,4 +3,4 @@
PY_FUNC(foo, foo, _foo); PY_FUNC(foo, foo, _foo);
PY_FUNC(bar, foo, _bar); PY_FUNC(bar, foo, _bar);
PY_FUNC(graph, foo, _complicated_function); PY_FUNC(graph, bar, _complicated_function);