Python Extension Designer / Builder.

eric jones eric at enthought.com
Fri Jan 25 15:49:45 EST 2002


Hey Gustavo,

weave has something like this built into it.  Instead of using XML, you
describe the module layout directly within Python.  It currently supports
extension functions.  classes/types are planned.  Type conversions are
handled by "type conversion factories" and can be customized to your needs.
Everything is done directly in Python.  Perhaps there is a benefit to XML
over this, but it isn't obvious to me.

Here is an example.

    # simple_ext_example.py
    def build_module():
        import weave

        # define the module
        mod = weave.ext_module('example_mod')

        # declare a function to put in the module
        a = 1 # this is effectively a type declaration
        ext_code = """
                   int val = a+1;
                   return_val = Py::new_reference_to(Py::Int(val));
                   """
        func = weave.ext_function('increment',ext_code,['a'])

        # add the function to the module
        mod.add_function(func)

        # compile it!
        mod.compile()

    if __name__ == '__main__':
        try:
            # try importing the module
            import example_mod
        except ImportError:
            # if it doesn't exist, build it.
            build_module()
            import example_mod

        print 'result (desired=2):', example_mod.increment(1)

And here is the output from running this from the command line:

C:\home\ej\wrk\junk\scipy\weave\examples>python simple_ext.py
example_mod.cpp
   Creating library
C:\DOCUME~1\eric\LOCALS~1\Temp\python21_intermediate\Release
\example_mod.lib and object
C:\DOCUME~1\eric\LOCALS~1\Temp\python21_intermediate
\Release\example_mod.exp
result (desired=2): 2

C:\home\ej\wrk\junk\scipy\weave\examples>python simple_ext.py
result (desired=2): 2

see ya,
eric






More information about the Python-list mailing list