Tuesday, July 03, 2007

Making Simple DLLs Simply

I often want to compile some simple C code and have it accessible from Python, but making DLLs and Python extensions for Windows has always been, for me, problematic.  Keeping this note brief and on a positive note....

Python extensions compiled using Microsoft tools need to be compiled using the same version as that used to compile Python itself.  If you don't have that version of Visual Studio or you want to also compile the extension for other versions of Python, having access to all the versions can be problematic.  I was successful in getting the mingw gcc to work for extensions, but when compiling what should be a small DLL (4K-8K for OSX and Linux), mingw created a bloated one, 742K.  For my purposes, that was a problem.  Bottom line: I went shopping for another compiler/linker.

After visiting The Free Country, I settled on the Digital Mars C (DMC) compiler.  It is a small, clean, fast ANSI C compiler, and generates code more like what I expected.  Creating DLLs was never fun, but DMC makes it really easy.  The license is short and easily understandable.  NB: The license expressly says the compiler is not tested, but I am assuming that is more for legal liability reasons.  Nevertheless, I will test my program; I advise you test yours.  That said....

To create a DLL, create a [sourcename].def file so it looks something like this.
    LIBRARY "[sourcename].dll"
    DESCRIPTION '[a short description]'
    EXETYPE NT
    SUBSYSTEM WINDOWS
    CODE SHARED EXECUTE
    DATA WRITE
    EXPORTS
        [functionname1]
        [functionname2]
        ...

Then execute this to create the DLL.
    dmc -WD [sourcename].c

Install the .dll file in a directory on your PATH and it should now be available to Python via ctypes.

Some themes and variations are possible so you might want to look at...
    Compiling Code
    Win32 Programming Guidelines
        (scroll to "Building and Using Windows DLLs", about 1/2 way down)
    DMC: Compiler

Oh, I almost forgot.  Digital Mars is Walter Bright, the creator of the D programming language. 

Labels: , ,