#include "Python.h"
int main()
{
Py_Initialize();
PyObject *pmodule = PyImport_ImportModule("os");
//获取当前用户的id
PyObject *pfunc = PyObject_GetAttrString(pmodule, "geteuid");
PyObject *arg = Py_BuildValue("()");
PyObject *result = PyObject_Call(pfunc, arg, NULL);
long retval = PyLong_AsLong(result);
printf("result: %ld\n", retval);
Py_XDECREF(result);
Py_FinalizeEx();
return 0;
}
gcc -c -I/usr/include/python3.10 -L/usr/lib/python3.10/config-3.10-x86_64-linux-gnu -L/usr/lib/x86_64-linux-gnu -lpython3.10 -lcrypt -ldl -lm -lm test.c
gcc -o test test.o -L/usr/lib/python3.10/config-3.10-x86_64-linux-gnu -L/usr/lib/x86_64-linux-gnu -lpython3.10 -lcrypt -ldl -lm
执行后返回如下:
$ ./test
result: 1001
这种方法可以调用普通Python函数