0

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.

2
  • You forgot to explain what the problem is, particularly with the phrase, program code is demo and non-working. Commented Jun 15, 2024 at 14:03
  • Calling PyRun_SimpleString("print(factorial(5))"); makes no sense. You should printf("%ld\n", factorial(5)); instead. Commented Jun 15, 2024 at 15:05

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.