Thursday, September 12, 2019

Quick help on Writing C Extension for Python

Here are a few links to the website which I think is helpful in doing this:

The below 3 link will help you understand the basic of building from window:

https://docs.python.org/3/extending/extending.html
https://docs.python.org/3/c-api/module.html#c.PyModuleDef
https://stackabuse.com/enhancing-python-with-custom-c-extensions/
https://stackoverflow.com/questions/49299905/error-lnk2001-unresolved-external-symbol-pyinit
https://docs.python.org/3/c-api/structures.html

After which, the challenge is to compile/link it to the Python project. The challenge I have is when compiling the code, you cannot just use a typical compiler from the IDE. Rather I found out that you have to use the relevant command prompt:
https://docs.python.org/3/extending/windows.html
https://docs.microsoft.com/en-us/cpp/build/how-to-enable-a-64-bit-visual-cpp-toolset-on-the-command-line?view=vs-2019

For example:

cl /LD /I <Path to Python36/inclulde> spammodule1.c <path to python36.lib>
e.g.
cl /LD /I C:\Users\username\AppData\Local\Programs\Python\Python36\include\  spammodule1.c C:\Users\username\AppData\Local\Programs\Python\Python36\libs\python36.lib


At this point, I got stucked because I am not able to proceed to how to use the DLL and LIB files.

However, I found out that you can also use the distutils method to compile into .py files:
https://docs.python.org/3/extending/building.html

For example:
<Python.exe path> setup.py build
C:\Users\username\AppData\Local\Programs\Python\Python36\python.exe setup.py build

I find this method easier as it will do compilation as well as typical installation that allow you to use it like any other Python Module. Do note however that you need to include the path into the Python Interface:

https://stackoverflow.com/questions/28326362/pycharm-and-pythonpath