Search code examples
pythonpython-c-api

Python gives error when importing simple C extension module


On windows I have built a very simple "hello world" C extension (the file hello.c from this site https://gist.github.com/physacco/2e1b52415f3a964ad2a542a99bebed8f). Using VS2015 I successfully obtain hello.dll. The problem is that I can't figure out how to import this file/module.

In the python shell (python 3.7) I have made sure that I'm in the same folder as the hello.dll. I have also made sure that sys.path() contains the folder path. But when I write "import hello" I get an error "ModuleNotFoundError: No module named 'hello'"

Does anyone has an idea of what is wrong is this very simple setup?

Update: When trying to import a module that does not exist the ModuleNotFoundError is reported. After renaming the hello.dll to hello.pyd an ImportError is returned. So it seems like it tries to actually load the module.


Solution

  • Python compiled modules on Windows have the extension .pyd, not .dll. If you'd built it using setup.py the file would be built with the correct name. However, you built it yourself and gave it a name that Python doesn't recognise as a module.


    In terms of the build command: you have to link it with libpython. You don't look to be doing this. The error you report is definitely one that you can get if the module is not linked against all its dependencies.

    I know you don't want to use setup.py, however I'd use it at least once just to see what it does and if it works. You'll then at least have a command that you can copy with a working set of options.