You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用SWIG将C程序转为Python时遇ImportError:动态模块未定义init函数

Fixing "ImportError: dynamic module does not define init function" with SWIG on Raspbian Stretch

I’ve run into this exact snag on Raspberry Pi before—let’s break down the common fixes step by step:

1. Double-Check Your SWIG Interface File (example.i)

First, confirm your .i file starts with the correct module declaration. This tells SWIG to generate the right initialization function Python expects:

%module example

For Python 2.x, this will create an initialization function named initexample—if your module name here doesn’t match what you’re trying to import, Python won’t find the function.

2. Compile Your C Code with Position-Independent Code

When you built example.o in Geany, you need to include the -fpic flag—this is required for code that gets packaged into a shared library. If you skipped this, recompile example.c with:

gcc -fpic -c example.c -o example.o

You can update your Geany build command to automatically include -fpic for future builds too.

3. Fix the Shared Library Linking Step

Your fourth command was cut off, but the key mistake here is usually an incorrect filename or missing objects. Python expects the shared library to be named _example.so (with the leading underscore) so that import example can load it in the background.

Run this full linking command:

gcc -shared example.o example_wrap.o -o _example.so

If you get linker errors about missing Python symbols, explicitly link against the Python 2.7 library:

gcc -shared example.o example_wrap.o -lpython2.7 -o _example.so

4. Test the Import Properly

Make sure both _example.so and the generated example.py are in the same directory as your script. Then import normally:

import example

Don’t try to import _example directly—that’s not how SWIG’s Python bindings are designed to work.

Full Working Flow Recap

To make sure you’re following the correct end-to-end process:

  • Create example.i with %module example at the top
  • Run swig -python example.i (generates example.py and example_wrap.c)
  • Compile your core C code: gcc -fpic -c example.c
  • Compile the SWIG wrapper: gcc -fpic -I/usr/include/python2.7 -c example_wrap.c
  • Link into the shared library: gcc -shared example.o example_wrap.o -o _example.so
  • Run your Python script that imports example

内容的提问来源于stack exchange,提问作者smajli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:24:17