Avatar ·

Calling C/C++ from Python: how to integrate native code into a Python project?

Hi everyone! I've been writing Python for about two years now, but recently I encountered a problem that stumped me. I need to speed up a computational module in my project. In Python it runs too slowly (loops with millions of iterations), and I decided to rewrite the critical part in C++.\n\nI wrote a simple C++ function for calculating Fibonacci numbers:\n\n```cpp\n// fibonacci.cpp\n#include \n\nextern "C" {\n int fibonacci(int n) {\n if (n <= 1) return n;\n int a = 0, b = 1, temp;\n for (int i = 2; i <= n; ++i) {\n temp = a + b;\n a = b;\n b = temp;\n }\n return b;\n }\n}\n```\n\nCompiled it into a DLL using MinGW: `g++ -shared -o fibonacci.dll fibonacci.cpp`\n\nNow I'm trying to call it from Python using ctypes:\n\n```