使用SWIG将C程序转为Python时遇ImportError:动态模块未定义init函数
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.iwith%module exampleat the top - Run
swig -python example.i(generatesexample.pyandexample_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

