Saved for later reference

online repository of stuff I had to google for hours to figure out

Simple Python ctypes Example – in Windows

Tags: , , , , , ,

I found this blog post, Simple Python ctypes Example, on Reddit, and thought I’d see how different the procedure was for Windows.

What you’ll need:

Creating the DLL

Create a file dlltest.c with the following content:

1
2
3
4
5
6
7
8
9
10
11
12
#include <windows.h>

BOOL APIENTRY DllMain(HANDLE hModule, DWORD dwReason, LPVOID lpReserved)
{
return TRUE;
}

__declspec(dllexport) int
multiply(int num1, int num2)
{
return num1 * num2;
}

Start the Visual Studio 2008 Command Prompt from the Start Menu (this sets up the path for the compiler and other files, which makes things easier) and go to the directory you saved dlltest.c to.

Compile it with the following command:

cl -LD dlltest.c -Fetest.dll

Testing the DLL

As in the original Linux example, this DLL is easily tested using similar commands:

1
2
3
4
>>> from ctypes import *
>>> libtest = cdll.LoadLibrary('test.dll')
>>> print libtest.multiply(2, 2)
4

So, that is the simplest DLL possible, I’ll look at (same as the original blog post) applying it to more complex examples later.

  • Share/Bookmark

Tags: , , , , , ,

2 Responses to “Simple Python ctypes Example – in Windows”


  1. swilly
    on Apr 26th, 2009
    @ 21:29

    Thanks for converting the example to Windows – I think a big problem with generating interest in extending Python with C is the lack of physical end-to-end examples available. They Python ctypes docs are great, but can be overwhelming. I think posts like this are much more useful to help people get their feet wet.


  2. lejordet
    on Apr 27th, 2009
    @ 18:03

    Exactly, that’s the reason I made this page :) Many things have really lacking documentation, and I think a minimal example like the one you posted is excellent for showing how little code is needed.

Leave a Reply

© 2009 Saved for later reference. All Rights Reserved.

This blog is powered by Wordpress and Magatheme by Bryan Helmig.