这应该是使用 SWIG、C 和 setuptools 的绝对最低限度的 Hello World。但导入模块时出现以下异常:
>>> 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)
这是目录结构:
README.md
pyproject.toml
src
src/hc
src/hc/hello.c
src/hc/hello.i
这里是
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"] }
]
这里是
hello.c
#include <stdio.h>
void say_hello() {
printf("Hello, World!\n");
}
这是接口文件:
%module hello
%{
void say_hello();
%}
void say_hello();
您的扩展模块应命名为 _hello(注意前导“_”)。
pyproject.toml:
# ...
[tool.setuptools]
ext-modules = [
{ name = "_hello", sources = ["src/hc/hello.c", "src/hc/hello.i"] }
]
检查:
[SO]:c 程序 SWIG 到 python 给出“导入错误:动态模块未定义 init 函数”(@CristiFati 的答案) 包含 SWIG 相关详细信息
[SO]:如何解决Python-C-API错误“这是上面提到的包的问题,而不是pip的问题。”? (@CristiFati 的回答) 包含有关使用 SetupTools
进行构建的信息