Created
January 29, 2023 03:51
-
-
Save ficapy/62e505d5d0cbbe48a1aeb496a1fec393 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Python.h> | |
static PyObject * fibonacci_fib(PyObject *self, PyObject *args) { | |
int n; | |
if (!PyArg_ParseTuple(args, "i", &n)) { | |
return NULL; | |
} | |
int i; | |
int a = 0; | |
int b = 1; | |
int c; | |
for (i = 0; i < n; i++) { | |
c = a + b; | |
a = b; | |
b = c; | |
} | |
return PyLong_FromLong(a); | |
} | |
static PyMethodDef methods[] = { | |
{"fib", fibonacci_fib, METH_VARARGS, "calculate fibonacci numbers"}, | |
{NULL, NULL, 0, NULL} | |
}; | |
static struct PyModuleDef fibonacci_module = { | |
PyModuleDef_HEAD_INIT, | |
"fibonacci_module", | |
"calculate fibonacci numbers", | |
-1, | |
methods | |
}; | |
PyMODINIT_FUNC PyInit_fibonacci_module(void) { | |
return PyModule_Create(&fibonacci_module); | |
} | |
int main(int argc, char *argv[]) { | |
wchar_t *program = Py_DecodeLocale(argv[0], NULL); | |
if (program == NULL) { | |
return 1; | |
} | |
Py_SetProgramName(program); | |
PyImport_AppendInittab("fibonacci_module", &PyInit_fibonacci_module); | |
Py_Initialize(); | |
PyImport_ImportModule("fibonacci_module"); | |
PyRun_SimpleString("import fibonacci_module\nprint(fibonacci_module.fib(30))"); | |
PyMem_RawFree(program); | |
return 0; | |
} | |
// bash -c "clang `python3.10-config --cflags` fib.c `python3.10-config --ldflags` -lpython3.10 -o fib" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment