I have the following module written in C using Python C-api:
#include <Python.h>
static PyObject* init_factorial(PyObject* self, PyObject* args) {
long long n;
if (!PyArg_ParseTuple(args, "l", &n)) {
return NULL;
}
if (n < 0) {
PyErr_SetString(PyExc_ValueError, "Factorial is not defined for negative numbers");
return NULL;
}
long result = 1;
for (long i = 1; i <= n; ++i) {
result *= i;
}
return PyLong_FromLong(result);
}
static PyMethodDef init_methods[] = {
{"factorial", init_factorial, METH_VARARGS, "Calculates the factorial of a number"},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef init_module = {
PyModuleDef_HEAD_INIT,
"init",
"Module for calculating factorial",
-1,
init_methods
};
static int init_init_module(PyObject *module) {
// some code ...
PyRun_SimpleString("print(factorial(5))");
return 0;
}
PyMODINIT_FUNC PyInit_init(void) {
PyObject *m = PyModule_Create(&init_module);
if (m == NULL)
return NULL;
// Call the function to print "factorial(5)" when importing
if (init_init_module(m) < 0) {
Py_DECREF(m);
return NULL;
}
return m;
}
The program code is demo and non-working.
How to modify the program code so that PyRun_SimpleString("print(factorial(5))");
printed the value of the factorial 5 to the console in the Python code space by calling the c-function factorial.
The code is executed immediately after importing the init module.