I'm trying out C to Python Extension using SWIG
For the toy application I've made following files
hw.chw.hhw.i
Contents of hw.h are
double hw1(double r1, double r2);
Contents of hw.c are
#include<hw.h> #include <math.h>
double hw1(double r1, double r2) {
return sin(r1 + r2);
}
Contents of hw.i are
%module mathModule
%{
#include <hw.h>
%}
%include<hw.h>
Can some one please explain me how to write this .i file?
Contents of setup.py
from distutils.core import setup, Extension
name = 'hw'
version = '1.0'
ext_modules_list = [Extension(name = '_mathModule', sources = ["hw.i","hw.c"], include_dirs=['.'])]
setup(name=name, version=version, ext_modules = ext_modules_list)
When I build the module, in iPython it gives me an error when I try following code
from mathModule import hw1
But the same thing works fine when I run in python shell
Also in the last line of setup.py, is setup a method and what is this way of passing parameters?
Also where the name of module is decided
This is the error I get in iPython
no module named _mathModule
Also can anyone say how should I specifyinclude_dirs in Extension class? I tried that it should look in present directory and thus placed . there
Thanks in advance :)
I do not know why you get different behavior in iPython vs python, but I can answer some of your other questions.
setup is a function provided by distutils.core and it is here called with keyword arguments. I usually write the call like this
but it is exactly equivalent to your call.
The setup file defines two modules, one called "hw" which is a python module, and one called "_mathModule" which is a compiled C extension. Both names are specified using the name keyword.
When you execute
python setup.py build, it generates you a directory build with two subdirectories build/temp* and build/lib* where * depends on the systems you compile the code for. If you investigate these directories, you should find build/lib*/hw.py and build/lib*/_mathModule.so. After building, these directories are NOT in your python path, so you need to do an extra step before you can import them in python. This is eitherpython setup.py installto copy the files to a system location where python can find them.The later three are only for development and testing. When distributing your code, you should always rely on the first option.
include_dirsare only used for compiling your extension. Once it is successfully built, the variable does not influence the search path for modules.