I am learning how to use swig to make a C extension for my Python code. And I use the code that I get from the website as an example. Here is my code:
example.c
#include <time.h>
double My_variable = 3.0;
int fact(int n) {
if (n <= 1) return 1;
else return n*fact(n-1);
}
int my_mod(int x, int y) {
return (x%y);
}
example.h
#ifndef EXAMPLE_H_
#define EXAMPLE_H_
extern double My_variable;
extern int fact(int n);
extern int my_mod(int x, int y);
#endif
example.i
%module example
%{
#define SWIG_FILE_WITH_INIT
#include "example.h"
%}
%#include "example.h"
Makefile
all:
rm -f *.so *.o *_wrap.* *.pyc
swig -python example.i
gcc -c -fPIC example_wrap.c -I/usr/include/python2.7
gcc -shared example_wrap.o -o _example.so
clean:
rm -f *.so *.o *_wrap.* *.pyc
test.py
import example
print str(example.fact(2))
Test.py is used to check if the extension is working. But when I run test.py, it outputs:
Traceback (most recent call last):
File "test.py", line 3, in <module>
print str(example.fact(2))
AttributeError: 'module' object has no attribute 'fact'
Here is the result when I use dir (example):
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '_example', '_newclass', '_object', '_swig_getattr', '_swig_property', '_swig_repr', '_swig_setattr', '_swig_setattr_nondynamic']
What is the reason for this conclusion?
If I want the program to run successfully, how do I do it?