Reputation: 1027
I am studying how to use swig to make a C expansion for my python code.And I use the code I get from website as 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
%{
/* Put header files here or function declarations like below */
#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))
The test.py is used to check if the expansion works.But when I run the test.py , it output:
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 output 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's the reason of this output appears?
If I want to the programme run successfully,how should I do?
Upvotes: 4
Views: 2536
Reputation: 33
Try changing the Makefile to
%module example
%{
#include "example.h"
%}
int fact(int n);
I've assumed you have only one method to export
Upvotes: 0
Reputation: 21
Please try to replace as below:
%#include "example.h"
by
%include "example.h"
Upvotes: 1