SamuraiT SamuraiT - 2 years ago 313
Python Question

ImportError: dynamic module does not define init function (initfizzbuzz)

I tried to compile

to import from python. For building
,I used
python build_ext -i

After building it, I tried to import
but the error below occurred.
How can I solve this problem ?


>>> import fizzbuzz
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: dynamic module does not define init function (initfizzbuzz)


#include <stdio.h>

void fizzbuzz(int n){

for (int i=1; i <= n; i++){
if (i % 3 == 0 && i % 5 ==0){
printf("fizzbuzz %d \n", i);
else if (i % 3 == 0){
printf("fizz %d \n", i);
else if(i % 5 == 0){
printf("buzz %d \n", i);

from distutils.core import setup, Extension
module = Extension('fizzbuzz', ['fizzbuzz.c'])

Answer Source

Python doesn't and cannot support arbitrary C files as modules. You'll have to follow certain conventions to let Python know what functions your module supports.

To do so, Python will look for a init<name> function, where <name> is the module name. Python was looking for initfizzbuzz but failed to find it, so loading the module failed.

Apart from an initialiser, you also need to provide a structure detailing what functions are available, and your function will need to handle Python types as arguments. Python provides you with the necessary utility functions and defines to make that easy enough.

I strongly urge you follow the Extending and Embedding the Python Interpreter tutorial. It teaches you everything you need to know to make your fizzbuzz C code work as a Python module.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download