66 lines
1.7 KiB
C
66 lines
1.7 KiB
C
#include <stdio.h>
|
|
|
|
#include <bash/builtins.h>
|
|
#include <bash/builtins/bashgetopt.h>
|
|
#include <bash/shell.h>
|
|
#include <dlfcn.h>
|
|
|
|
extern char **make_builtin_argv(WORD_LIST*, int*);
|
|
|
|
#define DEFINE_BUILTIN(name) \
|
|
struct builtin name##_struct = { \
|
|
#name, \
|
|
name##_builtin_func, \
|
|
BUILTIN_ENABLED, \
|
|
NULL, \
|
|
NULL, \
|
|
0 \
|
|
}
|
|
|
|
#define WRAP_FUNC_WITH_BUILTIN(name)\
|
|
int name##_builtin_func(WORD_LIST *list) { \
|
|
int argc, ret; \
|
|
char **argv; \
|
|
argv = make_builtin_argv(list, &argc); \
|
|
ret = name(argc, argv); \
|
|
free(argv); \
|
|
return ret;\
|
|
}
|
|
|
|
#define PY_FUNC(bash_name, modname, function) \
|
|
int bash_name(int argc, char **argv) { \
|
|
dlopen("libpython3.13.so", RTLD_NOW | RTLD_GLOBAL);\
|
|
if (!Py_IsInitialized()) { \
|
|
PyImport_AppendInittab(#modname, PyInit_##modname); \
|
|
Py_Initialize(); \
|
|
} \
|
|
int _##bash_name(int argc, char **argv) { \
|
|
int ret = 1; \
|
|
PyObject *mod = NULL, *func = NULL, *result; \
|
|
\
|
|
mod = PyImport_ImportModule(#modname); \
|
|
func = PyObject_GetAttrString(mod, #function); \
|
|
\
|
|
PyObject *py_argv = PyTuple_New(argc - 1); \
|
|
\
|
|
for (int i = 1; i < argc; i++) { \
|
|
PyObject *arg_as_str = PyUnicode_FromString(argv[i]); \
|
|
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); \
|
|
} \
|
|
WRAP_FUNC_WITH_BUILTIN(bash_name); \
|
|
DEFINE_BUILTIN(bash_name);
|