Search code examples
pythoncwindowsswig

Dynamic module does not define module export function(PyInit_example)


I was recently building a C extension for python using swig.

At first, I ran :

swig -python example.i

Then it generated example.py & example_wrap.c

After I ran:

gcc -c example.c example_wrap.c -I D:/path_to_python/Python/include

Ok, then it generated objects example.o & example_wrap.o

After I want to make a shared object file and ran :

gcc -o example.dll -s -shared example.o -Wl,--subsystem,windows

It generated example.dll. I renamed the extension of example.dll to example.pyd.Then copied and pasted example.pyd & example.py to Python\DLLs & Python\Lib folders respectively.

Till everything went good. But when I open python.exe and write import example and an error occurs. It says:

Dynamic module does not define module export function(PyInit_example).

I tried various things but not work. I want to generate .pyd from .dll.

I used :

-Windows 10

-Python310

-GCC MinGW 64

I appreciate those who help.


Solution

  • The final name should be _example.pyd (with underscore). You import example which loads the generated example.py, which then does import _example and loads _example.pyd. No need to copy anything into the Python subdirectories.

    Make sure the example.i file starts with %module example.

    I don't have MingGW installed but here's a command line build using VS2019:

    example.i

    %module example
    
    %inline %{
    int add(int a, int b) {
        return a + b;
    }
    %}
    

    Demo below. Note /Fe names the output file, and /LD creates a DLL.

    C:\demo>swig -python example.i
    
    C:\demo>cl /LD /Fe_example.pyd /Ic:\python38\include example_wrap.c -link -libpath:c:\python38\libs
    Microsoft (R) C/C++ Optimizing Compiler Version 19.29.30136 for x64
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    example_wrap.c
    Microsoft (R) Incremental Linker Version 14.29.30136.0
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    /dll
    /implib:_example.lib
    /out:_example.pyd
    -libpath:c:\python38\libs
    example_wrap.obj
       Creating library _example.lib and object _example.exp
    
    C:\demo>py
    Python 3.8.10 (tags/v3.8.10:3d8993a, May  3 2021, 11:48:03) [MSC v.1928 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import example
    >>> example.add(5,6)
    11
    

    Here's my best guess with MingGW (untested, since I don't have it installed):

    swig -python example.i
    gcc -c -fpic example.c example_wrap.c -Ipython3.9
    gcc -shared example.o example_wrap.o -o _example.pyd