December 14th 2007 11:52 am

Creating a Python module with Scons and SWIG

Some times ago, I proposed an optional build for SWIG if the SWIG binary was not found on the system. Here I propose an enhancement, a new library builder that will be registered in the environment env as PythonModule. It takes the same arguments as a classical SharedLibrary, but it does some additional steps :

  • It forces SWIG to create a Python wrapper (flag -python)
  • It checks if SWIG is present at all
  • It suppresses every prefix that the system might need (as lib in Linux)
  • On Windows and for Python >= 2.5, it changes the extension as pyd


Here is the code :

?View Code PYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import re
import sys
 
def SWIGSharedLibrary(env, library, sources, **args):
  swigre = re.compile('(.*).i')
  if env.WhereIs('swig') is None:
    sourcesbis = []
    for source in sources:
      cName = swigre.sub(r'\1_wrap.c', source)
      cppName = swigre.sub(r'\1_wrap.cc', source)
      if os.path.exists(cName):
        sourcesbis.append(cName)
      elif os.path.exists(cppName):
        sourcesbis.append(cppName)
      else:
        sourcesbis.append(source)
  else:
    sourcesbis = sources
 
  if 'SWIGFLAGS' in args:
    args['SWIGFLAGS'] += ['-python']
  else:
    args['SWIGFLAGS'] = ['-python'] + env['SWIGFLAGS']
  args['SHLIBPREFIX']=""
  if sys.version >= '2.5':
    args['SHLIBSUFFIX']=".pyd"
 
  cat=env.SharedLibrary(library, sourcesbis, **args)
  return cat
 
env['BUILDERS']['PythonModule'] = SWIGSharedLibrary

Once registered, a new SWIG module named mymodule can be created with :

env.PythonModule('_mymodule', ['myfile.i', 'myfile.c'])

2 Comments »

2 Responses to “Creating a Python module with Scons and SWIG”

  1. Mark Gritter on 25 Jun 2008 at 3:44 am #

    I’m a bit confused at registering a python function directly as a Builder, instead of creating a custom Builder with an action or generator. I’d like to do something similar (so I can use other builders like you use env.SharedLibrary), but I’m not sure this is a supported usage… What exactly goes on here?

  2. Matt on 25 Jun 2008 at 6:58 am #

    In fact, the real builder is still SharedLibrary for SCons. What I do is preprocess the sources in case SWIG is not available (I change .i for _wrap.c or _wrap.cc), and then I add ‘-python’ so that swig really understands it has to create a Python module. Finally, I change the library suffix and prefix if needed before I call the real builder, SharedLibrary.

Trackback URI | Comments RSS

Leave a Reply

You must be logged in to post a comment.

« Manifold learning toolbox for Python | Transforming a C++ vector into a Numpy array »