pythoncsetuptoolsswig

SWIG Hello World; ImportError: dynamic module does not define module export function


This is supposed to be the absolute minimum Hello World using SWIG, C, and setuptools. But the following exception is raised when the module is imported:

>>> import hello
Traceback (most recent call last):
  File "<python-input-0>", line 1, in <module>
    import hello
ImportError: dynamic module does not define module export function (PyInit_hello)

This is the directory structure:

README.md
pyproject.toml
src
src/hc
src/hc/hello.c
src/hc/hello.i

Here is the pyproject.toml

[build-system]
requires = ["setuptools>=75.6"]
build-backend = "setuptools.build_meta"

[project]
name = "helloc"
version = "0.0.1"
authors = [
    { name = "Foo" }
]
description = "Hello world SWIG C"
readme = "README.md"
requires-python = ">=3.13"
classifiers = [
    "Development Status :: 1 - Planning",
    "License :: Public Domain",
    "Natural Language :: English",
    "Operating System :: OS Independent",
    "Programming Language :: Python",
    "Programming Language :: Python :: 3",
    "Programming Language :: Python :: 3 :: Only",
    "Programming Language :: Python :: 3.13"
]

[tool.setuptools]
ext-modules = [
  { name = "hello", sources = ["src/hc/hello.c", "src/hc/hello.i"] }
]

Here is hello.c

#include <stdio.h>

void say_hello() {
    printf("Hello, World!\n");
}

And here is the interface file:

%module hello

%{
void say_hello();
%}

void say_hello();

Solution

  • Your extension module should be named _hello (notice the leading "_").

    pyproject.toml:

    # ...
    
    [tool.setuptools]
    ext-modules = [
      { name = "_hello", sources = ["src/hc/hello.c", "src/hc/hello.i"] }
    ]
    

    Check: